4.4. Getting the Length of a String
Problem
You need the length of a string.
Solution
Use string’s length member function:
std::string s = "Raising Arizona"; int i = s.length();
Discussion
Retrieving the length of a string is a trivial task, but it is a good opportunity to
discuss the allocation scheme for strings (both wide
and narrow character). strings, unlike C-style
null-terminated character arrays, are dynamically sized, and grow as needed. Most standard
library implementations start with an arbitrary (low) capacity, and grow by doubling the
capacity each time it is reached. Knowing how to analyze this growth, if not the exact
algorithm, is helpful in diagnosing string performance problems.
The characters in a basic_string are stored in a
buffer that is a contiguous chunk of memory with a static size. The buffer a string uses
is an arbitrary size initially, and as characters are added to the string, the buffer
fills up until its capacity is reached. When this happens, the buffer grows, sort of.
Specifically, a new buffer is allocated with a larger size, the characters are copied from
the old buffer to the new buffer, and the old buffer is deleted.
You can find out the size of the buffer (not the number of characters it contains, but
its maximum size) with the capacity member function. If
you want to manually set the capacity to avoid needless buffer copies, use the reserve member function and pass it a numeric argument that indicates the desired buffer size. There is a maximum size ...