3.5 Strings
The standard library provides a string type to complement the string literals used earlier. The string type provides a variety of useful string operations, such as concatenation. For example:
string s1 = "Hello"; string s2 = "world"; void m1() { string s3 = s1 + ", " + s2 + "!\n"; cout << s3; }
Here, s3 is initialized to the character sequence
Hello, world!
followed by a newline. Addition of strings means concatenation. You can add strings, string literals, and characters to a string.
In many applications, the most common form of concatenation is adding something to the end of a string. This is directly supported by the += operation. For example:
void m2(string& s1, string& s2) { s1 = s1 + '\n'; // append newline s2 += '\n'; // append newline }
The two ways of adding to the end of a string are semantically equivalent, but I prefer the latter because it is more concise and likely to be more efficiently implemented.
Naturally, strings can be compared against each other and against string literals. For example:
string incantation; void respond(const string& answer) { if (answer == incantation) { // perform magic } else if (answer == "yes") { // ... } // ... }
Among other useful features, the standard library string class provides the ability to manipulate substrings. For example:
string name = "Niels Stroustrup"; void m3() { string s = name.substr(6,10) ; // s = "Stroustrup" name.replace(0,5,"Nicholas") ; // name becomes "Nicholas Stroustrup" }
The substr() operation returns a string that is a copy of the substring indicated by its arguments. The first argument is an index into the string (a position), and the second argument is the length of the desired substring. Since indexing starts from 0, s gets the value Stroustrup.
The replace() operation replaces a substring with a value. In this case, the substring starting at 0 with length 5 is Niels; it is replaced by Nicholas. Thus, the final value of name is Nicholas Stroustrup. Note that the replacement string need not be the same size as the substring that it is replacing.
3.5.1 C-Style Strings
A C-style string is a zero-terminated array of characters. As shown, we can easily enter a C-style string into a string. To call functions that take C-style strings, we need to be able to extract the value of a string in the form of a C-style string. The c_str() function does that. For example, we can print the name using the C output function printf() like this:
void f() { printf("name: %s\n",name.c_str()) ; }