The string Type in C++

A string is a sequence of characters.

The char type represents only one character. To represent a string of characters, use the data type called string. For example, the following code declares that message to be a string with the value Programming is fun.

string message = “Programming is fun”;

The string type is not a primitive type. It is known as an object type. Here message represents a string object with contents Programming is fun.

Objects are defined using classes. string is a predefined class in the <string> header file. An object is also known as an instance of a class. Objects and classes will be thoroughly discussed in Chapter 9. For now, you need to know only how to create a string object, anc how to use the simple functions in the string class, as shown in Table 4.7.

The functions in the string class can only be invoked from a specific string instance. For this reason, these functions are called instance functions. For example, you can use the size() function in the string class to return the size of a string object and use the at(index) function to return the character at the specified index, as shown in the following code:

string message = “ABCD”;

cout    << message.1ength() <<  endl;

cout    << << endl;

string s = “Bottom”;

cout    << s.1ength() << endl;

cout    << << endl;

Invoking message.length() returns 4 and invoking returns character A. Invoking s.length() returns 6 and invoking returns character o.

The syntax to invoke an instance function is objectName.functionName(arguments). A function may have many arguments or no arguments. For example, the at(index) func­tion has one argument, but the length() function has no arguments.

1. String Index and Subscript Operator

The function can be used to retrieve a specific character in a string s, where the index is between 0 and s.1ength()-1. For example, returns the char-acter W, as shown in Figure 4.2. Note that the index for the first character in the string is 0.

Figure 4.2 The characters in a string object can be accessed using its index.

For convenience, C++ provides the subscript operator for accessing the character at a specified index in a string using the syntax stringName[index]. You can use this syntax to retrieve and modify the character in a string. For example, the following code sets a new character P at index 0 using s[0] = ‘P’ and displays it.

string s = “ABCD”;

s[0] = ‘P’;

cout << s[0] << endl;

2. Concatenating Strings

C++ provides the + operator for concatenating two strings. The statement shown below, for example, concatenates strings si and s2 into s3:

string s3 = si + s2;

The augmented += operator can also be used for string concatenation. For example, the following code appends the string “and programming is fun” with the string “Welcome to C++”in message.

message += ” and programming is fun”;

Therefore, the new message is “Welcome to C++ and programming is fun”.

You can also concatenate a character with a string. For example,

string s = “ABC”;

s += ‘D’;

Therefore, the new s is “ABCD” .

3. Comparing Strings

You can use the relational operators ==, !=, <, <=, >, >= to compare two strings. This is done by comparing their corresponding characters one by one from left to right. For example,

string si = “ABC”;

string s2 = “ABE”;

cout << (si == 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)

Consider evaluating s1 > s2. The first two characters (A versus A) from s1 and s2 are compared. Because they are equal, the second two characters (B versus B) are compared. Because they are also equal, the third two characters (C versus E) are compared. Since the character C is less than E, the comparison returns 0.

4. Reading Strings

A string can be read from the keyboard using the cin object. For example, see the following code:

  • string city;
  • cout << “Enter a city: “;
  • cin >> city; // Read to string city
  • cout << “You entered ” << city << endl;

Line 3 reads a string to city. This approach to reading a string is simple, but there is a prob­lem. The input ends with a whitespace character. If you want to enter New York, you have to use an alternative approach. C++ provides the getline function in the string header file, which reads a string from the keyboard using the following syntax:

getline(cin, s, delimitCharacter)

The function stops reading characters when the delimiter character is encountered. The delim­iter is read but not stored into the string. The third argument delimitCharacter has a default value (     ).

The following code uses the getline function to read a string.

  • string city; declare a string
  • cout << “Enter a city: ” ;
  • getline(cin, city, ‘\n’); // Same as getline(cin, city) read a string
  • cout << “You entered ” << city << endl;

Since the default value for the third argument in the getline function is ‘\n’, line 3 can be replaced by

getline(cin, city); // Read a string

Listing 4.7 gives a program that prompts the user to enter two cities and displays them alphabetically.

Listing 4.7 OrderTwoCities.cpp

1 #include <iostream>

2 #include <string>

3 using namespace std;


5 int main()

6 {

7    string city1, city2;

8    cout << “Enter the first city: “;

9    getline(cin, city1);

10    cout << “Enter the second city: “;

11    getline(cin, city2);


13    cout << “The cities in alphabetical order are “;

14    if (city1 < city2)

15    cout << city1 << ” ” << city2 << endl;

16    else

17    cout << city2 << ” ” << city1 << endl;


19    return 0;

20 }

When using strings in the program, you should always include the string header file (line 2). If line 9 is replaced by cin >> cityl, you cannot enter a string with spaces for cityl. Since a city name may contain multiple words separated by spaces, the program uses the getline function to read a string (lines 9, 11).

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 *