Make your own free website on Tripod.com

Tutorial 11

Manipulating Characters and Strings

 The instructor's notes for this tutorial will consist of the following:

Overview

This tutorial deals with the manipulation of characters and character strings. Various concepts will be presented that show how to manipulate string data. Some of these concepts include determining the number of characters contained in a string, concatenating strings, partial string manipulation, searching strings, as well as comparing string values. The use of the DOS window will also be presented.

 

Objectives

After completing the tutorial, the student will be able to:

Lecture Notes

Introduction to character manipulation and strings

In many situations it may be desirable for a program to manipulate, or process is some fashion, character and/or string data. Most programming languages provide built-in functions that make character and string manipulation a much easier task vs. the programmer writing his/her functions to perform this manipulation.

Note that most of the functions discussed in this tutorial will have more than one proper syntax. However, because the purpose of this tutorial is simply to introduce the student to character and string manipulation, only one syntax will typically be shown. If a function has more than one syntax, a tip stating that fact will be shown in the margin next to the explanation of the function.

 

Controlling the case of a character

Remember from tutorial 8 that character comparisons involving letters are case-sensitive. This is because each character has its own unique ASCII code. Since this presents a problem when users enter data that must be checked for a value (you do not know whether the data has been entered in uppercase or lowercase), the toupper and tolower functions can be used to aid in this problem. Rather than using a logical operator when comparing characters that represent letters, you can use a function that temporarily converts the letter to either uppercase or lowercase before the comparison is made. (Notice that the conversion is temporarily made, there is no permanent change to the data).

Below is the syntax for both the toupper and tolower functions. The toupper function converts a character to its uppercase equivalent, while the tolower function converts a character to its lowercase equivalent.

Syntax of the toupper function: toupper (charVariable)

Syntax of the tolower function: tolower (charVariable)

Note that in both functions, charVariable is the variable that contains the data you wish to convert. Also note that both functions will return a value that is of the character type. In addition, if either function is passed a value that is already in the desired case, the value will simply be returned back by the function. Also note that both functions only operate on data that corresponds to the letters of the alphabet, the functions have no effect on numbers and special characters.

See Figure 11-2 on page 381 for examples of both the toupper and tolower functions.

INSERT FIGURE 11-2

Controlling the case of a string

Like character comparisons, string comparisons are case-sensitive. Before using a string in a comparison, you can convert the entire string to either uppercase or lowercase by using the transform function. The syntax of the transform function is below:

transform (string.begin(), string.end(), string.begin(), function)

where

See Figure 11-4 on page 383 for an example of the transform function.

Determining the number of characters contained in a string

In many programs, it is necessary to determine the number of characters contained in a string. In some programming languages, the number of characters contained in a string is referred to as the size of the string, while in others it is referred to as the length of the string. In C++ the size function is used to determine how many characters are contained in a string. Below is the syntax for the size function:

string.size()

where string is the string you wish to determine how many characters are contained within it.

See Figure 11-7 on page 386 for an example of the size function.

Comparing a portion of a string variable's contents to another string

You remember from the tutorial on the relational structure, that you can use the comparison operators to compare two strings. However in some programs, rather than comparing two entire strings, you may need to compare a portion of one string to another string. In C++ the compare function is used to accomplish this task. The syntax of the compare function is below:

string1.compare(startCompare, numberOfCharsToCompare, string2)

where

(string1 is a string variable, while string2 can be a string literal or a string variable)

(can be a numeric literal constant, or the name of a numeric variable)

See Figure 11-9 on page 388 for example of the compare function.

Determining whether a string is contained within a string variable

Dependent upon your algorithm, it may be desirable to determine whether a specific string is contained within a string variable. The C++ function that accomplishes this task is the find function. The syntax of the find function is below:

string.find (subString, startFind)

where

(can be a string literal or the name of a string variable)

(can be a numeric literal or the name of a numeric variable)

See Figure 11-11 on pages 390-391 for example of the find function.

Replacing a portion of a string variable's contents

When you use the assignment operator to assign a string to a string variable, the string replaces all of the characters previously stored in the variable. In situations where you need to replace only a portion of a string variable's contents, rather than the entire contents, you need to use a function. The C++ function to accomplish this task is the replace function. The syntax of the replace function is below:

string.replace (startReplace, numberOfCharsToReplace, replacementString)

where

(can be a numeric literal or the name of a numeric variable)

(can be a numeric literal or the name of a numeric variable)

(can be a string literal or the name of a string variable)

See Figure 11-13 on page 394 for examples of the replace function.

 

Assigning a portion of one string variable to another string variable

You may use the assignment operator to assign the entire contents of one string variable to another string variable. However, in situations where you would like to assign a portion of one string to another string, you need to use a function. The C++ function to accomplish this task is the assign function. The syntax of the assign function is below:

destinationString.assign (sourceString, startAssign, numberOfCharsToAssign)

where

(can be a numeric literal or a numeric variable)

(can be a numeric literal or a numeric variable)

Note that the assign function changes only the contents of the destinationString, it does not change the contents of the sourceString.

See Figure 11-15 on page 395 for examples of the assign function.

Replicating a character and assigning it to a string variable

The C++ assign function also has a syntax that can be used to duplicate one character a specified number of times, and then assign the resulting string to a string variable. The syntax is below:

string.assign (number, character)

where

(may be a numeric literal or a numeric variable)

(may be a character literal or a character variable)

See Figure 11-16 on page 396 for examples of this version of the assign function.

Concatenating strings

Connecting (or linking) strings together is called concatenating. Most programming languages provide a special operator, called the concatenation operator, which you use to concatenate strings. The concatenation operator in C++ is the plus sign (+).

See Figure 11-18 on page 397 for examples of concatenation.

 

Discussion Topics/Additional Activities

Solutions to Questions

1. a toupper(insured)

2. c transform(state.begin(), state.end(), state.begin(), toupper);

3. a cout << address.size();

4. a result = address.compare(0, 4, "1123");

5. c 1

6. c result = state.find("CA", 5);

7. d 15

8. b code.replace(4, 2, "AB");

9. d partNum.assign(code, 0, 2);

10. a divider.assign(5, '*');

11. b cityState = city + ", " + state;

Solutions to Concept Lesson Exercises

 

1.

//T11ConE01.cpp - displays the square root of an integer

#include <iostream>

#include <cctype>

#include <cmath>

using namespace std;

int main()

{

//declare variables

char repeatLoop = 'Y';

int number = 0;

while (toupper(repeatLoop) == 'Y')

{

//get number, then display square root

cout << "Enter an integer: ";

cin >> number;

cout << "Square root: " << sqrt(number) << endl;

cout << "Repeat the loop (Y or N)? ";

cin >> repeatLoop;

} //end while

return 0;

} //end of main function

2.

//T11ConE02.cpp - displays the city and state in uppercase

#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

//declare variables

string city = "";

string state = "";

//get the city, then convert the city to uppercase

cout << "Enter a city (enter X to end the program): ";

getline(cin, city);

transform(city.begin(), city.end(), city.begin(), toupper);

while (city != "X")

{

//get the state, then convert the state to uppercase

cout << "Enter a state: ";

getline(cin, state);

transform(state.begin(), state.end(), state.begin(), toupper);

//display the city and state

cout << "City and State: " << city << ", " << state << endl;

//get the city, then convert the city to uppercase

cout << "Enter a city (enter X to end the program): ";

getline(cin, city);

transform(city.begin(), city.end(), city.begin(), toupper);

} //end while

return 0;

} //end of main function

 3.

//T11ConE03.cpp - displays a row of hyphens below one or more words

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variables

string displayString = "";

string hyphens = "";

//get one or more words

cout << "Enter one or more words: ";

getline(cin, displayString);

//assign hyphens

hyphens.assign(displayString.size(), '-');

//display word(s) and hyphens

cout << displayString << endl;

cout << hyphens << endl;

return 0;

} //end of main function

 

4.

//T11ConE04.cpp - displays a message or two characters

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variables

string character1 = "";

string character2 = "";

int compareValue = 0;

//get two characters

cout << "Character 1: ";

getline(cin, character1);

cout << "Character 2: ";

getline(cin, character2);

//display message or characters

compareValue = character1.compare(0, 1, character2);

if (compareValue == 0)

cout << "Equal" << endl;

else if (compareValue == -1)

cout << character1 << " " << character2 << endl;

else cout << character2 << " " << character1 << endl;

//end ifs

return 0;

} //end of main function

5.

//T11ConE05.cpp - displays the location of a string within a string

#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

//declare variables

string alphabet = "abcdefghijklmnopqrstuvwxyz";

string letters = "";

int location = 0;

//get a string

cout << "Enter one or more letters: ";

getline(cin, letters);

//convert the string to lowercase

transform(letters.begin(), letters.end(), letters.begin(), tolower);

//assign location of string to location variable

location = alphabet.find(letters, 0);

//display location

cout << letters << " begins in location " << location << endl;

return 0;

} //end of main function

 

 

6.

//T11ConE06.cpp - replaces a character within a string

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variable

string phone = "";

//get a phone number

cout << "Phone number (for example, 999-9999): ";

getline(cin, phone);

//replace hyphen with the empty string

phone.replace(3, 1, "");

//display phone number

cout << "Phone number: " << phone << endl;

return 0;

} //end of main function

 

7.

//T11ConE07.cpp - assigns a portion of a string to another string

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variables

string partNumber = "";

string item = "";

string color = "";

//get a part number

cout << "Enter a five-character part number: ";

getline(cin, partNumber);

//verify that the user entered five characters

if (partNumber.size() == 5)

{

//assign item and color

item.assign(partNumber, 0, 3);

color.assign(partNumber, 3, 2);

//display item and color

cout << "Item: " << item << endl;

cout << "Color: " << color << endl;

}

else

cout << "The part number must contain five characters." << endl;

//end if

return 0;

} //end of main function

 8.

//T11ConE08.cpp - concatenates strings and displays the result

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variables

string city = "";

string state = "";

string zip = "";

string cityStateZip = "";

//get a city, state, and zip

cout << "City? ";

getline(cin, city);

cout << "State? ";

getline(cin, state);

cout << "Zip code? ";

getline(cin, zip);

//concatenate the city, a comma, a space, the state, two spaces, and the zip

cityStateZip = city + ", " + state + " " + zip;

//display the concatenated string

cout << "Concatenated string: " << cityStateZip << endl;

return 0;

} //end of main function

9.

//T11ConE09.cpp - transforms a string and displays the results

#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

//declare variable

string state = "";

//get a state

cout << "State? ";

getline(cin, state);

//capitalize the first letter in the state

transform(state.begin(), state.begin() + 1, state.begin(), toupper);

//convert all letters in the state, other than the first letter, to lowercase

transform(state.begin() + 1, state.end(), state.begin() + 1, tolower);

//display the transformed string

cout << "Transformed string: " << state << endl;

return 0;

} //end of main function

10. Changes made to the original code are shaded.

/T11ConE10.cpp - displays a price based on the last character in the customer number

#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

//declare variable

string custNumber = "";

//get the customer number

cout << "Enter a 3-character customer number: ";

getline(cin, custNumber);

//verify that the user entered 3 characters

if (custNumber.size() == 3)

{

//convert to uppercase

transform(custNumber.begin(), custNumber.end(), custNumber.begin(), toupper);

//display the price

if (custNumber.compare(2, 1, "W") == 0)

cout << "Price: $50" << endl;

else if (custNumber.compare(2, 1, "X") == 0)

cout << "Price: $100" << endl;

else cout << "Price: $150" << endl;

} //end ifs

else

cout << "The customer number must contain 3 characters." << endl;

//end if

return 0;

} //end of main function

 

Solutions to Application Lesson Exercises

1.

//T11AppE01 - simplified version of the Hangman game

#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

//declare variables

string origWord = "";

string letter = "";

int position = 0;

int dashesReplaced = 0;

string guessWord = "";

int numberOfChars = 0;

//get the original word from player 1

cout << "Enter the original word: ";

getline(cin, origWord);

//determine the size of the original word

numberOfChars = origWord.size();

//convert the original word to uppercase

transform(origWord.begin(), origWord.end(), origWord.begin(), toupper);

//clear the contents of the DOS window

system("cls");

//assign and display the dashes in the guessed word

guessWord.assign(numberOfChars, '-');

cout << "Guess this word: " << guessWord << endl;

 

 

 

 

 

 

 

//repeat loop instructions while all dashes have not been replaced

while (dashesReplaced < numberOfChars)

{

//get a letter from player 2

cout << "Enter a letter: ";

cin >> letter;

//convert the letter to uppercase

transform(letter.begin(), letter.end(), letter.begin(), toupper);

//search for the letter in the original word

position = origWord.find(letter, 0);

//repeat while the letter is found in the original word

while (position >= 0)

{

//replace the appropriate dash with the letter

guessWord.replace(position, 1, letter);

//add 1 to the counter

dashesReplaced = dashesReplaced + 1;

//search for the letter in the remaining characters

position = origWord.find(letter, position + 1);

} //end while

//display the contents of the guessed word

cout << "Your guess: " << guessWord << endl;

} //end while

//display message indicating that the word has been guessed

cout << "Great job!" << endl;

return 0;

} //end of main function

2.

//T11AppE02.cpp - displays the color of an item

#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

//declare variables

string item = "";

string color = "";

cout << "Enter a 5-character item number: ";

getline(cin, item);

transform(item.begin(), item.end(), item.begin(), toupper);

while (item != "X")

{

//verify that user entered 5 characters

if (item.size() == 5)

{

//assign color letter

color.assign(item, 2, 1);

//display color

if (color == "B")

cout << "Blue" << endl;

else if (color == "G")

cout << "Green" << endl;

else if (color == "R")

cout << "Red" << endl;

else if (color == "W")

cout << "White" << endl;

else

cout << "Incorrect color letter" << endl;

//end ifs

}

else

cout << "The item number must contain 5 characters." << endl;

//end if

cout << "Enter a 5-character item number: ";

getline(cin, item);

transform(item.begin(), item.end(), item.begin(), toupper);

} //end while

return 0;

} //end of main function

3.

//T11AppE03.cpp - displays last name, a comma, a space, and first name

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variables

string name = "";

string first = "";

string last = "";

int spaceLoc = 0;

//get name

cout << "Enter first name, a space, and last name (9 to stop program): ";

getline(cin, name);

while (name != "9")

{

//locate space

spaceLoc = name.find(" ", 0);

//assign characters to left of space to first variable

first.assign(name, 0, spaceLoc);

//assign characters to right of space to last variable

last.assign(name, spaceLoc + 1, name.size() - spaceLoc - 1);

//display last, comma, space, and first

cout << last << ", " << first << endl;

//get another name

cout << "Enter first name, a space, and last name (9 to stop program): ";

getline(cin, name);

} //end while

return 0;

} //end of main function

4.

//T11AppE04.cpp - displays a phone number without any hyphens

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variables

string phone = "";

int hyphenLoc = 0;

//get phone number

cout << "Enter phone number (9 to stop program): ";

getline(cin, phone);

while (phone != "9")

{

//locate hyphens, then replace with empty string

hyphenLoc = phone.find("-", 0);

while (hyphenLoc >= 0)

{

phone.replace(hyphenLoc, 1, "");

hyphenLoc = phone.find("-", 0);

} //end while

//display phone number

cout << phone << endl;

//get another phone number

cout << "Enter phone number (9 to stop program): ";

getline(cin, phone);

} //end while

return 0;

} //end of main function

5.

//T11AppE05.cpp - compares a portion of a string to another string, and displays

//an appropriate message

#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

//declare variables

string name = "";

string searchFor = "";

int spaceLocation = 0;

int compareValue = 0;

//get the search name

cout << "Enter name (first name followed by a space and the last name): ";

getline(cin, name);

transform(name.begin(), name.end(), name.begin(), toupper);

//get the search text

cout << "Enter one or more characters as the search text (9 to end program): ";

getline(cin, searchFor);

while (searchFor != "9")

{

transform(searchFor.begin(), searchFor.end(), searchFor.begin(), toupper);

//locate the space in the search name

spaceLocation = name.find(" ", 0);

//compare the search text to the characters located after the space in the search name

compareValue = name.compare(spaceLocation + 1, searchFor.size(), searchFor);

//display appropriate message

if (compareValue == 0)

cout << "The last name begins with " << searchFor << endl;

else if (compareValue < 0)

cout << "The last name comes before " << searchFor << endl;

else cout << "The last name comes after " << searchFor << endl;

//end if

//get the search text

cout << "Enter one or more characters as the search text (9 to end program): ";

getline(cin, searchFor);

} //end while

return 0;

} //end of main function

6.

//T11AppE06.cpp - displays a random letter, and then allows the user to guess the letter

#include <iostream>

#include <string>

#include <algorithm>

#include <cstdlib>

#include <ctime>

using namespace std;

int main()

{

//declare variables

string letters = "abcdefghijklmnopqrstuvwxyz";

string randomLetter = "";

string letterGuess = "";

int randomNumber = 0;

//generate random number, then assign random letter from letters variable

srand(time(NULL));

randomNumber = 0 + rand() % (25 - 0 + 1);

randomLetter.assign(letters, randomNumber, 1);

//get letter guess from user

cout << "Letter guess? ";

getline(cin, letterGuess);

//verify that the user entered one letter

if (letterGuess.size() == 1)

{

while (letterGuess != randomLetter)

{

transform(letterGuess.begin(), letterGuess.end(), letterGuess.begin(), tolower);

//display appropriate message

if (letterGuess < randomLetter)

cout << "The correct letter comes after the letter " << letterGuess << "." << endl;

else

cout << "The correct letter comes before the letter " << letterGuess << "." << endl;

//end if

cout << "Letter guess? ";

getline(cin, letterGuess);

} //end while

cout << "You guessed the correct letter." << endl;

} //end if

else

cout << "Enter one letter only." << endl;

//end if

return 0;

} //end of main function

7.

//T11AppE07.cpp - simplified version of the Hangman game

#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

//declare variables

string origWord = "";

string letter = "";

int position = 0;

int dashPosition = 0;

string guessWord = "-----";

//get the original word from player 1

cout << "Enter the original word: ";

getline(cin, origWord);

//verify that the original word contains exactly 5 characters

if (origWord.size() != 5)

cout << "Enter a five-letter word" << endl;

else

{

//convert the original word to uppercase

transform(origWord.begin(), origWord.end(), origWord.begin(), toupper);

//clear the contents of the DOS window

system("cls");

//display the five dashes in the guessed word

cout << "Guess this word: " << guessWord << endl;

//repeat loop instructions while all dashes have not been replaced

while (dashPosition >= 0)

{

//get a letter from player 2

cout << "Enter a letter: ";

cin >> letter;

//convert the letter to uppercase

transform(letter.begin(), letter.end(), letter.begin(), toupper);

//search for the letter in the original word

position = origWord.find(letter, 0);

//repeat while the letter is found in the original word

while (position >= 0)

{

//replace the appropriate dash with the letter

guessWord.replace(position, 1, letter);

//search for the letter in the remaining characters

position = origWord.find(letter, position + 1);

} //end while

//display the contents of the guessed word

cout << "Your guess: " << guessWord << endl;

dashPosition = guessWord.find("-", 0);

} //end while

//display message indicating that the word has been guessed

cout << "Great job!" << endl;

} //end if

return 0;

} //end of main function

8.

//T11AppE08.cpp - inserts characters into a string

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variable

string phone = "";

//get the phone number

cout << "Enter phone number (without hyphens) ";

getline(cin, phone);

//determine size

if (phone.size() == 7)

phone.insert(3, "-");

else if (phone.size() == 10)

{

phone.insert(0, "(");

phone.insert(4, ") ");

phone.insert(9, "-");

} //end ifs

//display the phone number

cout << phone << endl;

return 0;

} //end of main function

9. Changes to the original code are shaded.

//T11AppE09.cpp - displays a portion of a string

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variables

string cityState = "";

string city = "";

int commaLocation = 0;

//get the city and state

cout << "Enter city, comma, space, and state: ";

getline(cin, cityState);

//locate comma

commaLocation = cityState.find(",", 0);

//assign city

city.assign(cityState, 0, commaLocation);

//display city

cout << "City: " << city << endl;

return 0;

} //end of main function