A standard string is essentially a resizable array of characters, with methods to perform substring searching and extraction, and overloaded operators to construct longer strings by concatenation. In the following table, cstr is an argument of type const string&, ch is an argument of type char, and i and n are arguments of type size_type (which is usually an unsigned long):
string(); // default constructor - empty string ("") string(cs); // C++ string from a C character string string(n,ch); // ch repeated n times. int size(); // number of characters int length(); // ditto int capacity(); // actual space available void reserve(n); // make space available string substr(i,n); // n chars from i (zero-based index) int find(cstr); // first cstr (npos if not found) int rfind(cstr); // last cstr int find(ch); // ditto, but for characters... int rfind(ch); void replace(i,n,cstr); // n chars after i replaced by cstr void append(cstr); // append cstr to the end string& operator += (cstr); // ditto string& operator += (ch); // ditto for characters bool operator==(cstr1,cstr2); string operator+(cstr1,cstr2);
The special constant string::npos is an unsigned value that is larger than any valid string length; it is β1 as a signed integer, which is why you occasionally see this value used. All the find() routines return npos on failure; if npos is used as a length (as in replace(2,string::npos,"help")), it means βto the end of the string.β
The key to building up strings efficiently is to note that std::string overallocates. The string's capacity() method is always greater than the size() method. You can explicitly ask for storage to be allocated by using reserve(). This prevents possibly expensive resizing operations, which usually involve copying. The following function shows the difference between size() and capacity() (code found in stdlib est-string.cpp).
void test_string() { string s; s.reserve(200); cout << "size = " << s.size() << " capacity = " << s.capacity() << endl; for(int i = 0; i < 80; i++) s += '*'; cout << "size = " << s.size() << " capacity = " << s.capacity() << endl; } size = 0 capacity = 200 size = 80 capacity = 200
You can get a character pointer from std::string by using c_str(). You should not keep this pointer because it usually becomes invalid when the string is destroyed.
18.191.68.18