//--------------------------------------------------------- // String Demo //--------------------------------------------------------- #include <iostream> using namespace std; int main() { // String constructors construct a string object having a // known state. string str1; // The new string object will store the // the empty string. string str2("String two"); // The new string object will store // the string indicated by the literal // string parameter. string str3(str2); // The new string object will have the // the same state as the string object // passed as a parameter. // Display the values of the three strings. The inserter operator is defined // for strings as part of the string class. cout << "String 1: " << str1 << endl; cout << "String 2: " << str2 << endl; cout << "String 3: " << str3 << endl << endl; // Assign new values to each string. The assignment operator is defined // for strings as part of the string class. str1 = "cat"; str2 = "Dog"; str3 = "horse"; cout << str1 << ' ' << str2 << " " << str3 << endl << endl; // Demonstrate relational operators. The relational operators are defined // for strings as part of the string class. cout << boolalpha; cout << str1 << " < " << str2 << " is " << (str1 < str2) << endl; cout << str1 << " <= " << str3 << " is " << (str1 <= str3) << endl << endl; // Demonstrate concatenation. The concatenation operator is defined // as part of the string class. str1 = "sea"; str2 = "horse"; str3 = str1 + str2; cout << str1 + " + " + str2 + ' ' + '=' + ' ' + str3 << endl << endl; // Determine the number of characters in the string cout << str1 << " is " << str1.length() << " characters long." << endl; cout << str2 << " is " << str2.length() << " characters long." << endl; cout << str3 << " is " << str3.length() << " characters long." << endl << endl; // Demonstrate how to access individual characters in a string using // the array subscript operator. for (unsigned int i = 0; i < str1.length(); i++) { cout << str1[i] << ' '; } cout << endl << endl; // Demonstrate how to access individual characters in a string using // the at() method. for (unsigned int i = 0; i < str1.length(); i++) { cout << str1.at(i) << ' '; } cout << endl << endl; // Determine the maximum number of positions in a string object. cout << "Maximum string length: " << str1.max_size() << endl << endl; return 0; }