//------------------------------------------------- // // Examples of string handling // // Simon Parsons // October 30th 2009 // //------------------------------------------------- // Include C++ library definitions #include // For input and output #include // To handle strings using namespace std; int main() { string s1 = "Hello"; string s2 = "Simon"; string s3, s4, s5; // Assign and print out s3 = s2; cout << s3 << endl; // Compare if(s1 == s3){ cout << "The same!" << endl; } else{ cout << "Different!" << endl; } if(s1 < s2){ cout << s1 << " is less than " << s2 << endl; } else{ cout << s1 << " is not less than " << s2 << endl; } // Concatenation s3 = s1 + " "; s3 += s2; cout << s3 << endl; // Read in strings cout << "Type a string with spaces" << endl; getline(cin, s4); cout << "I have: " << s4 << endl; cout << "Type a string with a comma that ends with a period" << endl; getline(cin, s4, ','); getline(cin, s5, '.'); cout << "I have: " << s4 << endl << s5 << endl; // Using a string as if it were an array s2[1] = 'u'; cout << s2 << endl; for(int i = 4; i >= 0; i--){ cout << s2[i]; } cout << endl; // Member functions cout << "s3 is " << s3.size() << " characters long" << endl; s3.replace(3, 2, "pp"); cout << "After replacing, s3 is: " << s3 << endl; s4 = s3.substr(6, 2); cout << "The substring is: " << s4 << endl; s3.erase(); cout << "After erasing, s3 is: " << s3 << endl; }