Altering strings

The string classes have standard container access methods, so you can access individual characters through a reference (read and write access) with the at method and [] operator. You can replace the entire string using the assign method, or swap the contents of two string objects with the swap method. Further, you can insert characters in specified places with the insert method, remove specified characters with the erase method, and remove all characters with the clear method. The class also allows you to push characters to the end of the string (and remove the last character) with the push_back and pop_back methods:

    string str = "hello"; 
cout << str << "n"; // hello
str.push_back('!'),
cout << str << "n"; // hello!
str.erase(0, 1);
cout << str << "n"; // ello!

You can add one or more characters to the end of a string using the append method or the += operator:

    string str = "hello"; 
cout << str << "n"; // hello
str.append(4, '!'),
cout << str << "n"; // hello!!!!
str += " there";
cout << str << "n"; // hello!!!! there

The <string> library also defines a global + operator that will concatenate two strings in a third string.

If you want to change characters in a string you can access the character through an index with the [] operator, using the reference to overwrite the character. You can also use the replace method to replace one or more characters at a specified position with characters from a C string or from a C++ string, or some other container accessed through iterators:

    string str = "hello"; 
cout << str << "n"; // hello
str.replace(1, 1, "a");
cout << str << "n"; // hallo

Finally, you can extract part of a string as a new string. The substr method takes an offset and an optional count. If the count of characters is omitted, then the substring will be from the specified position until the end of the string. This means that you can copy a left-hand part of a string by passing an offset of 0 and a count that is less than the size of the string, or you can copy a right-hand part of the string by passing just the index of the first character.

    string str = "one two three"; 
string str1 = str.substr(0, 3);
cout << str1 << "n"; // one
string str2 = str.substr(8);
cout << str2 << "n"; // three

In this code, the first example copies the first three characters into a new string. In the second example, the copying starts at the eighth character and continues to the end.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset