WvString Examples

WvString x("fuzzy wazoo");

In this case, a WvString object 'x' is created. "fuzzy wazoo" is a static string, meaning a const char * is passed to the constructor of 'x', so a dynamic string is created inside of 'x', and "fuzzy wazoo" is copied over. No call to unique() is necessary in this case.

When 'x' is destroyed (automatically upon exiting the C++ code block) the dynamic string will be deleted automatically.

WvString output("fuzzy %-10.3s %5s\n", "abcdef", 12);
WvString c(output);
c.edit()[1] = 'a';

The first command above creates a WvString called 'output' which contains the string "fuzzy abc[seven spaces] [three spaces]12\n". This uses the printf-like string formatting feature built into WvString. Note that unlike printf, WvString's formatter is type-safe: you can't pass the wrong kind of object to the formatter. In fact, everything you format must use a '%s' format string - %d, %f, etc are not supported.

The above function call works as follows: new WvStrings are allocated for the first two parameters ("fuzzy..." and "abcdef"). Then it turns '12' into a WvString using the WvString::WvString(int) constructor. All three operations require dynamic memory allocations.

C++ then passes the new WvStrings on to the WvString "complex" constructor, which formats them according to the first string and generates an output string, which is always dynamically allocated.

The second line above creates a WvString 'c' which is the same as 'output'. It does not cause any new dynamic memory allocations to occur and is very quick.

The third line first makes 'c' unique (so that it has a separate copy of the output string), then changes the second character to 'a', so that now 'c' contains "fazzy abc 12" and output contains "fuzzy abc 12".

WvString nul;

This command creates a null WvString. This is NOT simply a WvString containing a zero-length string, but a WvString that points to nothing. You very seldom want to leave a WvString this way, but if you do, you can test for this condition simply by comparing it to NULL:

(nul == NULL)

A zero-length WvString differs slightly from a null WvString. You can declare one as follows:

WvString zerolen("");

The following expression will be true:

(zerolen == "")

However, 'zerolen' will not be equal to NULL. Conversely, a null WvString is not equal to the zero-length string, "".

Most often, you will want to immediately fill a null WvString with an empty buffer with setsize(), as below.

WvString newstr;
newstr.setsize(128);
sprintf(newstr.edit(), "blah blah %5.4f", floatval);

These commands first create a NULL WvString, then attach it to an uninitialized 128-byte buffer. We then use sprintf to fill the string buffer.