The C++ String
/* * This is a useless program to play with string. */ #include <iostream> #include <string> using namespace std; main() { // Prompt and request a uselsess word. cout << "What's your favorite word today? "; string word; cin >> word; // Comment on its start and end. cout << "You chose the word \"" << word << ".\"" << endl; cout << "Your exciting word starts with " << word[0] << " and ends " << "with " << word[word.length()-1] << endl; // Comment on its various parts. int half = word.length() / 2; cout << "The second half of your word is " << word.substr(half) << ". The first half is " << word.substr(0,half) << "." << endl; // Check on foo. Sort of thing you just have to have around. int pos = word.find("foo"); if(pos == string::npos) { cout << "There is no foo in your word. " << endl; // Put it somewhere, but be careful not to pick an // out-of-bounds location. int loc = 3; if(loc >= word.length()) loc = 0; word = word.substr(0,loc) + "FOO" + word.substr(loc); cout << word << ". That's better." << endl; } else { cout << "Your excellent word contains foo at position " << pos << "." << endl; } }

The string type in C++ is simpler to use than the one in Java. In particular, strings can be compared using the normal comparison operators, rather then needing equals and compareTo. They also can be subscripted like arrays to select individual characters.

C++ strings are also mutable, which means there are methods which update them in place. You can also place the subscript notation on the left of an assignment, updating particular characters in the string. Consult your textbook or an online reference for full documentation of the string facility.

Of course, string is not a basic type, but is provided by the run-time library. That is why you need to #include its header.