Additional String Member Functions
The string class overloads many operators and
has numerous (over a hundred) member functions.
- The length or size member function returns an unsigned integer value
that gives the number of characters currently in the string.
The string class actually defines a data type called size_type to store
the length or size of a string.
An example:
string firstname, fullname;
firstname << "George";
cout < < firstname.length( ) < < endl;
// prints 6
fullname = firstname + " Warren Bush";
cout < < fullname.size( ) < < endl;
// prints 18
-
The find member function searches a string to find the first occurrence
of a particular substring and returns an unsigned integer value
giving the result of the search. The substring passed as an argument to the
function, can be a literal string or a string expression. For example:
str1.find("hand count")
str1.find(str2)
str1.find("no " + str2)
In each case, str1 is searched to see if the specified substring can be
found within it. If so, the function returns the position in str1 where
the match begins. If the substring could not be found, the function returns
the special value string::npos, a named constant whose value is the largest
possible value of type string::size_type
(a number like 4294967295) as a
sentinel. Given the code segment:
string phrase:
string::size_type position;
phrase = "The dog and the cat";
position = phrase.find("the"); // assigned the value of 12
position = phrase.find("rat"); // assigned the value of
string::npos
The argument to the find function can also be a char value. In this case,
the function find
searches for the first occurrence of that character within the string and
returns its position, or string::npos if the character was not found.
For example:
string theString;
theString = "Abracadabra";
cout < < theString.find('a');
// prints 3
The default starting position for the search is 0. This can be changed
by supplying a second argument:
str1.find(str2, pos)
Starting at position pos, the function searches the string str1
for the first occurrence of the substring str2, and returns the position
in str1 where the match begins.
This enables us to find multiple occurrences of a substring within a source string.
-
The member function erase removes characters from the string:
str.erase(pos, len);
removes a substring of length len starting at position pos.
-
The member function insert inserts a substring str2 in the string
str1 starting at position pos:
str1.insert(pos, str2);
-
The member function append appends a substring to the end of a string:
str1.append(str2)
The substring str2 is appended to str1, and the resulting string is
returned in string str1.