10.2 Using the Overloaded Operators of Standard Library Class string

Figure 10.1 demonstrates many of class string’s overloaded operators and several other useful member functions, including empty, substr and at. Function empty determines whether a string is empty, function substr (for “substring”) returns a string that’s a portion of an existing string and function at returns the character at a specific index in a string (after checking that the index is in range). Chapter 21 presents class string in detail.




Fig. 10.1 Standard Library string class test program.

Alternate View

 1   // Fig. 10.1: fig10_01.cpp
 2   // Standard Library string class test program.
 3   #include <iostream>
 4   #include <string>
 5   using namespace std;
 6
 7   int main() {
 8      string s1{"happy"};
 9      string s2{" birthday"};
10      string s3; // creates an empty string
11
12      // test overloaded equality and relational operators
13      cout << "s1 is "" << s1 << ""; s2 is "" << s2
14         << ""; s3 is "" << s3 << '"'
15         << "

The results of comparing s2 and s1:" << boolalpha
16         << "
s2 == s1 yields " << (s2 == s1)
17         << "
s2 != s1 yields " << (s2 != s1)
18         << "
s2 >  s1 yields " << (s2 > s1)
19         << "
s2 <  s1 yields " << (s2 < s1)
20         << "
s2 >= s1 yields " << (s2 >= s1)
21         << "
s2 <= s1 yields " << (s2 <= s1);
22
23      // test string member function empty
24      cout << "

Testing s3.empty():
";
25
26      if (s3.empty()) {
27         cout << "s3 is empty; assigning s1 to s3;
";
28         s3 = s1; // assign s1 to s3
29         cout << "s3 is "" << s3 << """;
30      }
31
32       // test overloaded string concatenation assignment operator
33      cout << "

s1 += s2 yields s1 = ";
34      s1 += s2; // test overloaded concatenation
35      cout << s1;
36
37      // test string concatenation with a C string
38      cout << "

s1 += " to you" yields
";
39      s1 += " to you";
40      cout << "s1 = " << s1;
41
42      // test string concatenation with a C++14 string-object literal
43      cout << "

s1 += ", have a great day!" yields
";
44      s1 += ", have a great day!"s; // s after " for string-object literal
45      cout << "s1 = " << s1 << "

";
46
47      // test string member function substr
48      cout << "The substring of s1 starting at location 0 for
"
49         << "14 characters, s1.substr(0, 14), is:
"
50         << s1.substr(0, 14) << "

";
51
52      // test substr "to-end-of-string" option
53      cout << "The substring of s1 starting at
"
54         << "location 15, s1.substr(15), is:
" << s1.substr(15) << "
";
55
56      // test copy constructor
57      string s4{s1};
58      cout << "
s4 = " << s4 << "

";
59
60      // test overloaded copy assignment (=) operator with self-assignment
61      cout << "assigning s4 to s4
";
62      s4 = s4;
63      cout << "s4 = " << s4;
64
65      // test using overloaded subscript operator to create lvalue
66      s1[0] = 'H';
67      s1[6] = 'B';
68      cout << "

s1 after s1[0] = 'H' and s1[6] = 'B' is:
"
69         << s1 << "

";
70
71      // test subscript out of range with string member function "at"
72      try {
73         cout << "Attempt to assign 'd' to s1.at(100) yields:
";
74         s1.at(100) = 'd'; // ERROR: subscript out of range
75      }
76      catch (out_of_range& ex) {
77         cout << "An exception occurred: " << ex.what() << endl;
78      }
79   }

s1 is "happy"; s2 is " birthday"; s3 is ""

The results of comparing s2 and s1:
s2 == s1 yields false
s2 != s1 yields true
s2 > s1 yields false
s2 < s1 yields true
s2 >= s1 yields false
s2 <= s1 yields true

Testing s3.empty():
s3 is empty; assigning s1 to s3;
s3 is "happy"

s1 += s2 yields s1 = happy birthday

s1 += " to you" yields
s1 = happy birthday to you

s1 += ", have a great day!" yields
s1 = happy birthday to you, have a great day!

The substring of s1 starting at location 0 for
14 characters, s1.substr(0, 14), is:
happy birthday

The substring of s1 starting at
location 15, s1.substr(15), is:
to you, have a great day!

s4 = happy birthday to you, have a great day!

assigning s4 to s4
s4 = happy birthday to you, have a great day!

s1 after s1[0] = 'H' and s1[6] = 'B' is:
Happy Birthday to you, have a great day!

Attempt to assign 'd' to s1.at(100) yields:
An exception occurred: invalid string position

Creating string Objects and Displaying Them with cout and Operator <<

Lines 8–10 create three string objects:

  • s1 is initialized with the literal "happy",

  • s2 is initialized with the literal " birthday" and

  • s3 uses the default string constructor to create an empty string.

Lines 13–14 output these three objects, using cout and operator <<, which the string class designers overloaded to handle string objects.

Comparing string Objects with the Equality and Relational Operators

Lines 15–21 show the results of comparing s2 to s1 by using class string’s overloaded equality and relational operators, which perform lexicographical comparisons (that is, like a dictionary ordering) using the numerical values of the characters in each string (see Appendix B, ASCII Character Set).

Normally, when you output a condition’s value 0 is displayed for false or 1 for true. However, we used the stream manipulator boolalpha (line 15) to set the output stream to display condition values as the strings "false" and "true".

string Member Function empty

Line 26 uses string member function empty, which returns true if the string is empty; otherwise, it returns false. The object s3 was initialized with the default constructor, so it is indeed empty.

string Copy Assignment Operator

Line 28 demonstrates class string’s overloaded copy assignment operator by assigning s1 to s3. Line 29 outputs s3 to demonstrate that the assignment worked correctly.

string Concatenation and C++14 string-object Literals

Line 34 demonstrates class string’s overloaded += operator for string concatenation assignment. In this case, the contents of s2 are appended to s1, thus modifying its value. Then line 35 outputs the resulting string that’s stored in s1. Line 39 demonstrates that you also may append a C-string literal to a string object by using operator +=. Line 40 displays the result.

Similarly, line 44 concatenates s1 with a C++14 string-object literal which is indicated by placing the letter s immediately following the closing " of a string literal, as in


", have a great day!"s

The preceding literal actually results in a call to a C++ Standard Library function that returns a string object containing the literal’s characters. Line 45 displays the new value of s1.

string Member Function substr

Class string provides member function substr (lines 50 and 54) to return a string containing a portion of the string object on which the function is called. The call in line 50 obtains a 14-character substring (specified by the second argument) of s1 starting at position 0 (specified by the first argument). The call to substr in line 54 obtains a substring starting from position 15 of s1. When the second argument is not specified, substr returns the remainder of the string on which it’s called.

string Copy Constructor

Line 57 creates string object s4 and initializes it with a copy of s1. This calls class string’s copy constructor, which copies the contents of s1 into the new object s4. You’ll see how to define a custom copy constructor for your own class in Section 10.10.

Testing Self-Assignment with the string Copy Assignment Operator

Line 62 uses class string’s overloaded copy assignment (=) operator to demonstrate that it handles self-assignment properly—we’ll see when we build class Array later in the chapter that self-assignment can be dangerous for objects that manage their own memory, and we’ll show how to deal with the issues. Line 63 confirms that s4 still has the same value after the self-assignment.

string Class [] Operator

Lines 66–67 use class string’s overloaded [] operator to create lvalues that enable new characters to replace existing characters in s1. Lines 68–69 output the new value of s1. Class string’s overloaded [] operator does not perform any bounds checking. Therefore, you must ensure that operations using class string’s overloaded [] operator do not accidentally manipulate elements outside the bounds of the string. Class string does provide bounds checking in its member function at, which throws an exception if its argument is an invalid subscript. If the subscript is valid, function at returns the character at the specified location as a modifiable lvalue or a nonmodifiable lvalue (e.g., a const reference), depending on the context in which the call appears. For example:

  • If at is called on a non-const string object, the function returns a modifiable lvalue, which could be used on the left of an assignment (=) operator to assign a new value to that location in the string.

  • If at is called on a const string object, the function returns a nonmodifiable lvalue that can be used to obtain, but not modify, the value at that location in the string.

Line 74 demonstrates a call to function at with an invalid subscript; this throws an out_of_range exception.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset