Object-Oriented Thinking in C++: The string Class

The string class defines the string type in C++. It contains many useful functions for manipulating strings.

In C++ there are two ways to process strings. One way is to treat them as arrays of characters ending with the null terminator (‘\0’), as discussed in Section 7.11, “C-Strings.” These are known as C-strings. The null terminator indicates the end of the string, which is important for the C-string functions to work. The other way is to process strings using the string class. You can use the C-string functions to manipulate and process strings, but the string class is easier. Processing C-strings requires the programmer to know how characters are stored in the array. The string class hides the low-level storage from the programmer. The programmer is freed from implementation details.

Section 4.8, “The string Type,” briefly introduced the string type. You learned how to retrieve a string character using the at(index) function and the subscript operator [], and use the size() and length() functions to return the number of characters in a string. This section gives a more detailed discussion on using string objects.

1. Constructing a String

You created a string using a syntax like this:

string s = “Welcome to C++”;

This statement is not efficient because it takes two steps. It first creates a string object using a string literal and then copies the object to s.

A better way to create a string is to use the string constructor like this:

string s(“Welcome to C++”);

You can create an empty string using string’s no-arg constructor. For example, the follow­ing statement creates an empty string:

string s;

You can also create a string from a C-string using string’s constructor as shown in the fol­lowing code:

char s1[] = “Good morning”;

string s(s1);

Here si is a C-string and s is a string object.

2. Appending to a String

You can use several overloaded functions to add new contents to a string, as shown in Figure 10.1.

For example:

string s1(“Welcome”);

s1.append(” to C++”); // Appends ” to C++” to si

cout << si << endl; // si now becomes Welcome to C++


string s2(“Welcome”);

s2.append(” to C and C++”, 0, 5); // Appends ” to C” to s2

cout << s2 << endl; // s2 now becomes Welcome to C


string s3(“Welcome”);

s3.append(” to C and C++”, 5); // Appends ” to C” to s3

cout << s3 << endl; // s3 now becomes Welcome to C


string s4(“Welcome”);

s4.append(4, ‘G’); // Appends “GGGG” to s4

cout << s4 << endl; // s4 now becomes WelcomeGGGG


3. Assigning a String

You can use several overloaded functions to assign new contents to a string, as shown in Figure 10.2.

For example:

string s1(“Welcome”);

s1.assign(“Dallas”); // Assigns “Dallas” to si

cout << s1 << endl; // s1 now becomes Dallas


string s2(“Welcome”);

s2.assign(“Dallas, Texas”, 0, 5); // Assigns “Dalla” to s2

cout << s2 << endl; // s2 now becomes Dalla


string s3(“Welcome”);

s3.assign(“Dallas, Texas”, 5); // Assigns “Dalla” to s3

cout << s3 << endl; // s3 now becomes Dalla


string s4(“Welcome”);

s4.assign(4, ‘G’); // Assigns “GGGG” to s4

cout << s4 << endl; // s4 now becomes GGGG


4. Functions at, clear, erase, and empty

You can use the at(index) function to retrieve a character at a specified index, clear() to clear the string, erase(index, n) to delete part of the string, and empty() to test whether a string is empty, as shown in Figure 10.3.

For example:

string s1(“Welcome”);

cout << s1.at(3) << endl; // s1.at(3) returns c

cout << s1.erase(2, 3) << endl; // s1 is now Weme

s1.clear(); // s1 is now empty

cout << s1.empty() << endl; // s1.empty returns 1 (means true)

5. Functions length, size, capacity, and c_str()

You can use the functions length(), size(), and capacity() to obtain a string’s length, size, and capacity and c_str() to return a C-string, as shown in Figure 10.4. The functions length() and size() are aliases. The functions c_str() and data() are the same in the new C++11. The capacity() function returns the internal buffer size which is always greater than or equal to the actual string size.

For example, see the following code:

1 string s1(“Welcome”);
2 cout << s1.length() << endl;
// Length is 7
3 cout << s1.size() << endl; // Size is 7
4 cout << s1.capacity() << endl; // Capacity is 15
6 s1.erase(
1, 2);
7 cout << s1.length() << endl;
// Length is now 5
8 cout << s1.size() << endl; // Size is now 5
9 cout << s1.capacity() << endl; // Capacity is still 15

6. Comparing Strings

Often, in a program, you need to compare the contents of two strings. You can use the compare function. This function returns an int value greater than 0, 0, or less than 0 if this string is greater than, equal to, or less than the other string, as shown in Figure 10.5

For example:

string s1(“Welcome”); string s2(“Welcomg”);

cout << s1.compare(s2) << endl; // Returns -1

cout << s2.compare(s1) << endl; // Returns 1

cout << s1.compare(“Welcome”) << endl; // Returns 0

7. Obtaining Substrings

You can obtain a single character from a string using the at function. You can also obtain a substring from a string using the substr function, as shown in Figure 10.6.

For example:

string s1(“Welcome”);
cout << s1.substr(
0, 1) << endl; // Returns W

cout << s1.substr(3) << endl; // Returns come
cout << s1.substr(3, 3) << endl; // Returns com

8. Searching in a String

You can use the find function to search for a substring or a character in a string, as shown in Figure 10.7. The function returns string::npos (not a position) if no match is found. npos is a constant defined in the string class.

For example:

string s1(“Welcome to HTML”);
cout << s1.find(
“co”) << endl; // Returns 3
cout << s1.find(“co”, 6) << endl; // Returns string::npos
cout << s1.find(‘o’) << endl; // Returns 4
cout << s1.find(‘o’, 6) << endl; // Returns 9

9. Inserting and Replacing Strings

You can use the insert and replace functions to insert a substring and replace a substring in a string, as shown in Figure 10.8.

Here are examples of using the insert and replace functions:

string s1(“Welcome to HTML”);
“C++ and “);
cout << s1 << endl; /
/ s1 becomes Welcome to C++ and HTML

string s2(“AA”);
1, 4, ‘B’);
cout << s2 << endl;
// s2 becomes to ABBBBA
string s3(“Welcome to HTML”);

s3.replace(11, 4, “C++”);
cout << s3 << endl;
// s3 becomes Welcome to C++

10. String Operators

C++ supports operators to simplify string operations. Table 10.1 lists the string operators

Here are the examples to use these operators:

string s1 = “ABC”; // The = operator
string s2 = s1; // The = operator
for (int i = s2.size() – 1; i >= 0; i–)
cout << s2[i];
// The [] operator

string s3 = s1 + “DEFG”; // The + operator
cout << s3 << endl; // s3 becomes ABCDEFG

s1 += “ABC”;
cout << s1 << endl;
// s1 becomes ABCABC

s1 = “ABC”;
s2 =
cout << (s1 == s2) << endl;
// Displays 0 (means false)
cout << (s1 != s2) << endl; // Displays 1 (means true)
cout << (s1 > s2) << endl; // Displays 0 (means false)
cout << (s1 >= s2) << endl; // Displays 0 (means false)
cout << (s1 < s2) << endl; // Displays 1 (means true)
cout << (s1 <= s2) << endl; // Displays 1 (means true)

11. Converting Numbers to Strings

Section 7.11.6, “Conversion between Strings and Numbers,” introduced how to convert a string to an integer and a floating-point number using the functions atoi and atof. You can also use the i toa function to convert an integer to a string. Sometimes you need to convert a floating-point number to a string. You can write a function to perform the conversion. How­ever, a simple approach is to use the stringstream class in the <sstream> header. stri ng- stream provides an interface to manipulate strings as if they were input/output streams. One application of stri ngstream is for converting numbers to strings. Here is an example:

1 stringstream ss;

2 ss << 3.1415;

3 string s = ss.str();

12. Splitting Strings

Often you need to extract the words from a string. Assume that the words are separated by whitespaces. You can use the stringstream class discussed in the preceding section to accomplish this task. Listing 10.1 gives an example that extracts the words from a string and displays the words in separate lines.

Listing IQ.! ExtractWords.cpp

1 #include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
7 {
8    string text(
“Programming is fun”);
9    stringstream ss(text);
11   cout <<
“The words in the text are ” << endl;
12   string word;
while (!ss.eof())
14   {
15      ss >> word;
16      cout << word << endl;
17   }
return 0;
20 }

The program creates a stringstream object for the text string (line 9) and this object can be used just like an input stream for reading data from the console. It sends data from the string stream to a string object word (line 15). The eof() function in the stringstream class returns true when all items in string stream are read (line 13).

13. Case Study: Replacing Strings

In this case study, you will write the following function that replaces the occurrence of a substring ol dSubStr with a new substring newSubStr in the string s.

bool rep1aceString(string& s, const string& oldSubStr,

const string& newSubStr)

The function returns true if string s is changed, and otherwise, it returns false.

Listing 10.2 gives the program.

Listing 10.2 ReplaceString.cpp

1 #include <iostream>
#include <string>
using namespace std;
// Replace oldSubStr in s with newSubStr
6 bool replaceString(string& s, const string& oldSubStr,
const string& newSubStr);
int main()
10 {
// Prompt the user to enter s, oldSubStr, and newSubStr
12    cout << “Enter string s, oldSubStr, and newSubStr: “;
13    string s, oldSubStr, newSubStr;
14    cin >> s >> oldSubStr >> newSubStr;
bool isReplaced = replaceString(s, oldSubStr, newSubStr);
if (isReplaced)
19       cout <<
“The replaced string is ” << s << endl;
21       cout << “No matches” << endl;
return 0;
24 }
bool replaceString(string& s, const string& oldSubStr,
const string& newSubStr)
28 {
bool isReplaced = false;
int currentPosition = 0;
while (currentPosition < s.length())
32    {
int position = s.find(oldSubStr, currentPosition);
if (position == string::npos) // No more matches
35        return isReplaced;
37        {
38            s.replace(position, oldSubStr.length(), newSubStr);
39            currentPosition = position + newSubStr.length();
40            isReplaced =
true; // At least one match
41        }
42    }
return isReplaced;
45 }

The program prompts the user to enter a string, an old substring, and a new substring (line 14). The program invokes the repalceString function to replace all occurrences of the old substring with the new substring (line 16) and displays a message indicating whether the string has been replaced (lines 18-21).

The replaceString function searches for oldSubStr in string s starting from currentPosition starting from 0 (line 30). The find function in the string class is used to find a substring in a string (line 33). It returns string::npos if it is not found. In this case, the search ends and the function returns isReplaced (line 35). isReplaced is a bool variable and initially set to false (line 29). Whenever a match for a substring is found, it is set to true (line 40).

The function repeatedly finds a substring and replaces it with a new substring using the replace function (line 38) and resets the current search position (line 39) to look for a new match in the rest of the string.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *