< Previous | Contents | Next >

Introducing the String Tester

Program

The String Tester program uses the string object equal to "Game Over!!!" and tells you its length, the index (position number) of each character, and whether or not certain substrings can be found in it. In addition, the program erases parts of the string object. Figure 3.3 shows the results of the program.


image

Figure 3.3

String objects are combined, changed, and erased through familiar operators and string member functions.

90 Chapter 3 n For Loops, Strings, and Arrays: Word Jumble


You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 3 folder; the filename is string_tester.cpp.

// String Tester

// Demonstrates string objects


#include <iostream> #include <string>


using namespace std;


int main()

{

string word1 = "Game"; string word2("Over"); string word3(3, ’!’);


string phrase = word1 + " " + word2 + word3; cout << "The phrase is: " << phrase << "\n\n";


cout << "The phrase has " << phrase.size() << " characters in it.\n\n"; cout << "The character at position 0 is: " << phrase[0] << "\n\n";

cout << "Changing the character at position 0.\n"; phrase[0] = ’L’;

cout << "The phrase is now: " << phrase << "\n\n";


for (unsigned int i = 0; i < phrase.size(); ++i)

{

cout << "Character at position " << i << " is: " << phrase[i] << endl;

}



cout << "\nThe sequence ’Over’ begins at location "; cout << phrase.find("Over") << endl;

Using String Objects 91

if (phrase.find("eggplant") == string::npos)

{

cout << "’eggplant’ is not in the phrase.\n\n";

}


phrase.erase(4, 5);

cout << "The phrase is now: " << phrase << endl;


phrase.erase(4);

cout << "The phrase is now: " << phrase << endl;


phrase.erase();

cout << "The phrase is now: " << phrase << endl;


if (phrase.empty())

{

cout << "\nThe phrase is no more.\n";

}


return 0;

}