next up previous contents
Next: Performance Tuning Up: Parsing and Formatting Previous: Find & Replace   Contents

Subsections

Formatting

format

void format(const char* templ, ...);

The format() function allows the construction of string data via "printf" style format specifiers. The implementation for format() actually calls a variation of sprintf() so full functionality is provided. If the string's current buffer is not large enough to hold the resulting string, format() function will automatically reallocate a buffer that is large enough.

One interesting and somewhat humorous aspect of format() is that it is not familiar with the Str type. This means that, if using Str objects as parameters, it is important to cast the objects to const char*, the same as with other printf()-like functions.

Str x = "An Equation";
Str y;
y.format("%s: %u + %u = %u\n", (const char*)x,
         4, 5, 4+5);
// y is now: "An Equation: 4 + 5 = 9"

lower, upper

void upper();
void lower();

The lower() and upper() functions will make a string all capital or all lower case. This is mainly useful when searching for a string without concern for case. Here is a working (but slightly inefficient) example that replaces all occurrences of a string without being sensitive to case:

void replaceNoCase(Str& str, const Str& from, const Str& to) {

    Str str_upper = str;
    str_upper.upper();
    Str from_upper = from;
    from_upper.upper();
    int idx_delta = 0;

    int idx = 0;
    while ((idx = str_upper.findNext(from_upper, idx)) >= 0) {
        str.replaceRange(idx + idx_delta, 
                         idx + from.length() + idx_delta, 
                         to);
        idx_delta += to.length() - from.length();
        idx += from.length();
    }
    
}



2007-05-05