Note that, if you plan on calling append()
or insert()
a number of times on a
given string, consider calling setTimeEfficient(true)
or resize(new_expected_size + 1)
on the
string. This will reduce buffer reallocations.
inline void append(const char* cstr); inline void append(const Str& str);
The append()
function will add the given substring to the end of
the current string. It is slightly faster to use the append(const Str& str)
form of append over the append(const char* cstr)
form because the second form needs to call
strlen(cstr)
before the copy operation to determine if
the current string buffer is large enough. The append()
function operates with efficiency.
Str x = "Hello"; Str y = "There"; x.append(" "); // x = "Hello "; x.append(y); // x = "Hello There";
inline void insert(const char* cstr, unsigned long idx); inline void insert(const Str& str, unsigned long idx);
The insert()
function will insert the given substring into the
current string. This function is efficient. If you pass an
idx
greater to or equal to the string's length, insert
will emulate the append
function.
Str x = "There"; Str y = "Hello"; x.insert(y,0); // x = "HelloThere"; x.insert(" ", 5); // x = "Hello There";
insert()
operates with efficiency.
inline void replaceRange(unsigned long start_idx, unsigned long end_idx, const char* cstr); inline void replaceRange(unsigned long start_idx, unsigned long end_idx, const Str& str);
The replaceRange
function is the "Swiss Army Knife" of string
manipulation functions in that it can insert substrings, delete substrings,
append substrings, or perform combinations of the two in one
command. replaceRange()
replaces the given range, non
inclusive, with the given string. Here are some examples of
replaceRange()
used in different roles:
Str x = "I really like pizza"; // Insert example Str y = x; y.replaceRange(1, 1, " really"); // y = I really really like pizza // Delete example y = x; y.replaceRange(1, 8, ""); // y = I like pizza // Append Example y = x; unsigned long ln = y.length(); y.replaceRange(ln, ln, "!"); // y = I really like pizza! // Replace Example y = x; y.replaceRange(9, 13, "love"); // y = I love pizza
If the string grows beyond the current string's buffer size as a result
of calling replaceRange
, the buffer will automatically be
reallocated.
A question you may have at this point is: If replaceRange()
can emulate insert()
and
append()
, why even have an insert()
and append()
?
This is a good question that I thought about for a while. In the end, I
prefer to have insert()
and append()
because they map well
from libraries, work in a more intuitive way, and execute slightly more
efficiently than replaceRange
does.
Note that there is also a string-search-based replace
function that you
may want to use instead of this one.
The replaceRange()
function operates with efficiency.