Skip to main content

2.11) String in C++: Useful Operations


A number of useful operations can be invoked on strings, including the following:

length Returns the length of the string
append Appends a string or characters to the string
insert Inserts a string or characters into the string
find Searches for a sequence of characters within the string
substr Returns part of this string as a new string
replace Replaces a sequence of characters with another sequence
c_str Returns this string's characters as a low-level 'C' string (discussed later)

These are methods of the string type. To invoke them on a string variable, you must append a period and the method name to the variable, followed by parentheses. Any values that the method needs to do its work must be supplied as a comma-separated list inside the parentheses. For example, the length of a string called s can be printed with

cout << s.length();

and we can append characters to s with

s.append("xyz");