The C++ String
#include <iostream> #include <string> using namespace std; int main() { // Use the getline method to enter a line. It's part of iostream. string line; cout << "Please enter a line:" << endl; cout << "> "; getline(cin, line); // Using the input operator to read a string enters a single word, // delimited by spaces. string word; cout << "Please enter a single word: "; cin >> word; // Printing is presumably what you would expect. cout << "You entered " << word << " and " << line << std::endl; // C++ strings can be compared with normal comparison operators. if(word == "wombat") cout << "You entered \"wombat\". My favorite word!" << endl; // The find operation searches for one string in another, and returns // the position, or string::npos, which is a symbolic constant. int loc = line.find(word); if(loc == string::npos) cout << "Your word is not in your line. Oh well." << endl; else cout << "Your word is at " << loc << " in your line." << endl; // Strings in C can be treated as arrays, and subscripted. for(int i = 0; i < word.length(); ++i) { cout << "-" << word[i] << "- "; } cout << 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.

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.

This example uses some control constructs we have not discussed, but they should be familiar from Java.

Textbook: Chapter 2, pp. 66—74

[more info]