The ANSI string class implements a first-class character string data type that avoids many problems associated with simple character arrays ("C-style strings"). You can define a string object very simply, as shown in the following example:
#include <string> using namespace std; ... string first_name = "Bjarne"; string last_name; last_name = "Stroustrup"; string names = first_name + " " + last_name; cout << names << endl; names = last_name + ", " + first_name; cout << names << endl; |
The string class defines many member functions. A few of the basic ones are described below:
Note: The string class is based on
a template class named basic_string.
Some of the member
function declarations below may be a little confusing
to those new to C++,
even though they have been simplified somewhat.
Fortunately, these functions
are quite easy to use in practice.
Initialization (constructor) | A string object may defined without an initializing value, in
which case its initial value is an empty string (zero length, no
characters):string str1; A string object may also be initialized with
|
length
size |
size_type length() const; size_type size() const; Both of these functions return the length (number of characters) of the string. The size_type return type is an unsigned integral type. (The type name usually must be scoped, as in string::size_type.) string str = "Hello"; string::size_type len; len = str.length(); // len == 5 len = str.size(); // len == 5 |
c_str | const char* c_str() const; For compatibility with "older" code, including some C++ library routines, it is sometimes necessary to convert a string object into a character array ("C-style string"). This function does the conversion. For example, you might open a file stream with a user-specified file name: string filename; cout << "Enter file name: "; cin >> filename; ofstream outfile (filename.c_str()); outfile << "Data" << endl; |
insert | string& insert(size_type pos, const string&
str); Inserts a string into the current string, starting at the specified position. string str11 = "abcdefghi"; string str12 = "0123"; str11.insert (3,str12); cout << str11 << endl; // "abc0123defghi" str12.insert (1,"XYZ"); cout << str12 << endl; // "0XYZ123" |
erase | string& erase(size_type pos, size_type n); Delete a substring from the current string. string str13 = "abcdefghi"; str12.erase (5,3); cout << str12 << endl; // "abcdei" |
replace | string& replace(size_type pos, size_type n, const string&
str); Delete a substring from the current string, and replace it with another string. string str14 = "abcdefghi"; string str15 = "XYZ"; str14.replace (4,2,str15); cout << str14 << endl; // "abcdXYZghi" |
find
rfind |
size_type find (const string& str, size_type
pos); Search for the first occurrence of the substring str in the current string, starting at position pos. If found, return the position of the first character. If not, return a special value (called string::npos). The member function rfind does the same thing, but returns the position of the last occurrence of the specified string. string str16 = "abcdefghi"; string str17 = "def"; string::size_type pos = str16.find (str17,0); cout << pos << endl; // 3 pos = str16.find ("AB",0); if (pos == string::npos) cout << "Not found" << endl; |
substr | string substr (size_type pos, size_type n); Returns a substring of the current string, starting at position pos and of length n: string str18 = "abcdefghi" string str19 = str18.substr (6,2); cout << str19 << endl; // "gh" |
In addition to member functions of the string class, some non-member functions are designed to work with strings; the most common of these is:
getline | istream& getline (istream& is, string& str, char delim
= '\n'); Reads characters from an input stream into a string, stopping when one of the following things happens:
The return value is a reference to the input stream. If the stream is tested as a logical value (as in an if or while), it is equivalent to true if the read was successful and false otherwise (e.g., end of file). The most common use of this function is to do "line by line" reads from a file. Remember that the normal extraction operator (>>) stops on white space, not necessarily the end of an input line. The getline function can read lines of text with embedded spaces. vector<string> vec1; string line; vec1.clear(); ifstream infile ("stl2in.txt"); while (getline(infile,line,'\n')) { vec1.push_back (line); } |
A number of C++ operators also work with string objects:
= | The assignment operator may be used in several ways:
|
+ | The "plus" operator concatenates:
|
+= | The "+=" operator combines the above assignment and concatenation
operations in the way that you would expect, with a string
object, a string literal, or a single character as the value on the
right-hand side of the operator. string str1 = "Hello "; str1 += "there"; |
== != < > <= >= |
The comparison operators return a Boolean (true/false) value
indicating whether the specified relationship exists between the two
operands. The operands may be:
|
<< | The insertion operator writes the value of a string object to
an output stream (e.g., cout). string str1 = "Hello there"; cout << str1 << endl; |
>> | The extraction operator reads a character string from an input stream
and assigns the value to a string object. string str1; cin >> str1; |
[]
(subscript) |
The subscript operator accesses one character in a string: string str10 = "abcdefghi"; char ch = str10[3]; cout << ch << endl; // 'd' str10[5] = 'X'; cout << str10 << endl; // "abcdeXghi" |
This document was written by Dr. Mark J. Sebern (See stl) and last updated on April 16, 1999