58
1 Starting Out with C++, 3 rd Edition Chapter 10 – Characters, Strings, and the string Class

Chapter 10 – Characters, Strings, and the string Class

  • Upload
    orrin

  • View
    78

  • Download
    4

Embed Size (px)

DESCRIPTION

Chapter 10 – Characters, Strings, and the string Class. 10.1 Character Testing. The C++ library provides several macros for testing characters. Be sure to include ctype.h header file. Table 10-1. Program 10-1. // This program demonstrates some of the character testing // functions . - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 10 – Characters, Strings, and the  string  Class

1

Starting Out with C++, 3rd Edition

Chapter 10 – Characters, Strings, and the string Class

Page 2: Chapter 10 – Characters, Strings, and the  string  Class

2

Starting Out with C++, 3rd Edition

10.1 Character Testing

• The C++ library provides several macros for testing characters.– Be sure to include ctype.h header file

Page 3: Chapter 10 – Characters, Strings, and the  string  Class

3

Starting Out with C++, 3rd Edition

Table 10-1CharacterMacro

Description

is a lp h a Returns true (a nonzero number) if the argument is a letter of the alphabet.Returns 0 if the argument is not a letter.

is a ln u m Returns true (a nonzero number) if the argument is a letter of the alphabet or adigit. Otherwise it returns 0.

isd ig it Returns true (a nonzero number) if the argument is a digit 0–9. Otherwise itreturns 0.

is lo w e r Returns true (a nonzero number) if the argument is a lowercase letter.Otherwise, it returns 0.

isp r in t Returns true (a nonzero number) if the argument is a printable character(including a space). Returns 0 otherwise.

isp u n c t Returns true (a nonzero number) if the argument is a printable character otherthan a digit, letter, or space. Returns 0 otherwise.

isu p p e r Returns true (a nonzero number) if the argument is an uppercase letter.Otherwise, it returns 0.

is sp a c e Returns true (a nonzero number) if the argument is a whitespace character.Whitespace characters are any of the following:

Page 4: Chapter 10 – Characters, Strings, and the  string  Class

4

Starting Out with C++, 3rd Edition

Program 10-1// This program demonstrates some of the character testing// functions. #include <iostream.h>#include <ctype.h>

void main(void){

char input;

cout << "Enter any character: ";cin.get(input);cout << "The character you entered is: " << input << endl;cout << "Its ASCII code is: " << int(input) << endl;

Page 5: Chapter 10 – Characters, Strings, and the  string  Class

5

Starting Out with C++, 3rd Edition

Program continues

if (isalpha(input))cout << "That's an alphabetic character.\n";

if (isdigit(input))cout << "That's a numeric digit.\n";

if (islower(input))cout << "The letter you entered is lowercase.\n";

if (isupper(input))cout << "The letter you entered is uppercase.\n";

if (isspace(input))cout << "That's a whitespace character.\n";

}

Page 6: Chapter 10 – Characters, Strings, and the  string  Class

6

Starting Out with C++, 3rd Edition

Program Output With Example inputEnter any character: A [Enter]The character you entered is: AIts ASCII code is: 65That's an alphabetic character.The letter you entered is uppercase.Program Output With Other Example inputEnter any character: 7 [Enter]The character you entered is: 7Its ASCII code is: 55That's a numeric digit.

Page 7: Chapter 10 – Characters, Strings, and the  string  Class

7

Starting Out with C++, 3rd Edition

Program 10-2// This program tests a customer number to determine if it is// in the proper format.#include <iostream.h>#include <ctype.h>

// Function prototypebool testNum(char []);

void main(void){

char customer[8];cout << "Enter a customer number in the form ";cout << "LLLNNNN\n";cout << "(LLL = letters and NNNN = numbers): ";cin.getline(customer, 8);

Page 8: Chapter 10 – Characters, Strings, and the  string  Class

8

Starting Out with C++, 3rd Edition

Program continuesif (testNum(customer))

cout << "That's a valid customer number.\n";else{

cout << "That is not the proper format of the ";cout << "customer number.\nHere is an example:\n";cout << " ABC1234\n";

}}

// Definition of function testNum. bool testNum(char custNum[]){

// Test the first three characters for alphabetic lettersfor (int count = 0; count < 3; count++){

Page 9: Chapter 10 – Characters, Strings, and the  string  Class

9

Starting Out with C++, 3rd Edition

Program continues

if (!isalpha(custNum[count]))return false;

}// Test the last 4 characters for numeric digitsfor (int count = 3; count < 7; count++){

if (!isdigit(custNum[count]))return false;

}return true;

}

Page 10: Chapter 10 – Characters, Strings, and the  string  Class

10

Starting Out with C++, 3rd Edition

Program Output With Example inputEnter a customer number in the form LLLNNNN(LLL = letters and NNNN = numbers): RQS4567 [Enter]That's a valid customer number.Program Output With Other Example inputEnter a customer number in the form LLLNNNN(LLL = letters and NNNN = numbers): AX467T9 [Enter]That is not the proper format of the customer number.Here is an example: ABC1234

Page 11: Chapter 10 – Characters, Strings, and the  string  Class

11

Starting Out with C++, 3rd Edition

10.2 Character Case Conversion

• The C++ library offers functions for converting a character to upper or lower case.– Be sure to include ctype.h header file

Page 12: Chapter 10 – Characters, Strings, and the  string  Class

12

Starting Out with C++, 3rd Edition

Table 10-2

Function Description

to u p p e r Returns the uppercase equivalent of its argument.

to lo w e r Returns the lowercase equivalent of its argument.

Page 13: Chapter 10 – Characters, Strings, and the  string  Class

13

Starting Out with C++, 3rd Edition

Program 10-3// This program calculates the area of a circle. It asks the// user if he or she wishes to continue. A loop that// demonstrates the toupper function repeats until the user// enters 'y', 'Y', 'n', or 'N'.#include <iostream.h>#include <ctype.h>

void main(void){

const float pi = 3.14159;float radius;char go;

cout << "This program calculates the area of a circle.\n";cout.precision(2);cout.setf(ios::fixed);

Page 14: Chapter 10 – Characters, Strings, and the  string  Class

14

Starting Out with C++, 3rd Edition

Program continues

do{

cout << "Enter the circle's radius: ";cin >> radius;cout << "The area is " << (pi * radius * radius);cout << endl;do{

cout << "Calculate another? (Y or N) ";cin >> go;

} while (toupper(go) != 'Y' && toupper(go) != 'N');} while (toupper(go) == 'Y');

}

Page 15: Chapter 10 – Characters, Strings, and the  string  Class

15

Starting Out with C++, 3rd Edition

Program Output With Example inputThis program calculates the area of a circle.Enter the circle's radius: 10 [Enter]The area is 314.16Calculate another? (Y or N) b Enter]Calculate another? (Y or N) y [Enter]Enter the circle's radius: 1 [Enter]The area is 3.14Calculate another? (Y or N) n [Enter]

Page 16: Chapter 10 – Characters, Strings, and the  string  Class

16

Starting Out with C++, 3rd Edition

10.3 Review of the Internal Storage of C-strings

• A C-string is a sequence of characters stored in consecutive memory locations, terminated by a null character.

Figure 10-1

Page 17: Chapter 10 – Characters, Strings, and the  string  Class

17

Starting Out with C++, 3rd Edition

Program 10-4// This program contains string constants#include <iostream.h>

void main(void){

char again;

do{

cout << "C++ programming is great fun!" << endl;cout << "Do you want to see the message again?

";cin >> again;

} while (again == 'Y' || again == 'y');}

Page 18: Chapter 10 – Characters, Strings, and the  string  Class

18

Starting Out with C++, 3rd Edition

Program 10-5// This program cycles through a character array, displaying// each element until a null terminator is encountered.#include <iostream.h>

void main(void){

char line[80];int count = 0;

cout << "Enter a sentence of no more than 79 characters:\n";cin.getline(line, 80);cout << "The sentence you entered is:\n";while (line[count] != '\0'){

cout << line[count];count++;

}}

Page 19: Chapter 10 – Characters, Strings, and the  string  Class

19

Starting Out with C++, 3rd Edition

Program Output with Example inputEnter a sentence of no more than 79 characters:C++ is challenging but fun! [Enter]The sentence you entered is:C++ is challenging but fun!

Page 20: Chapter 10 – Characters, Strings, and the  string  Class

20

Starting Out with C++, 3rd Edition

10.4 Library Functions for Working with C-strings

• The C++ library has numerous functions for handling C-strings These functions perform various tests and manipulations.

• Functions discussed in this section require the inclusion of string.h header file

Page 21: Chapter 10 – Characters, Strings, and the  string  Class

21

Starting Out with C++, 3rd Edition

Figure 10-2

Page 22: Chapter 10 – Characters, Strings, and the  string  Class

22

Starting Out with C++, 3rd Edition

Table 10-3Function Description s trlen Accepts a C-string or a pointer to a string as an argument. Returns the length of the

string (not including the null terminator. Example Usage: len = strlen(name); s trc a t Accepts two C-strings or pointers to two strings as arguments. The function appends

the contents of the second string to the first string. (The first string is altered, the second string is left unchanged.) Example Usage: strcat(string1, string2);

s trc p y Accepts two C-strings or pointers to two strings as arguments. The function copies the second string to the first string. The second string is left unchanged. Example Usage: strcpy(string1, string2);

s trn c p y Accepts two C-strings or pointers to two strings and an integer argument. The third argument, an integer, indicates how many characters to copy from the second string to the first string. If the string2 has fewer than n characters, string1 is padded with '\0 ' characters. Example Usage: strncpy(string1, string2, n);

s trc m p Accepts two C-strings or pointers to two string arguments. If string1 and string2are the same, this function returns 0. If string2 is alphabetically greater than string1, it returns a negative number. If string2 is alphabetically less than string1, it returns a positive number. Example Usage: if (strcmp(string1, string2))

s trs tr Accepts two C-strings or pointers to two C-strings as arguments, searches for the first occurrence of string2 in string1. If an occurrence of string2 is found, the function returns a pointer to it. Otherwise, it returns a NULL pointer (address 0). Example Usage: cout << strstr(string1, string2);

Page 23: Chapter 10 – Characters, Strings, and the  string  Class

23

Starting Out with C++, 3rd Edition

Program 10-6// This program uses the strstr function to search an array// of strings for a name.#include <iostream.h>#include <string.h> // For strstr

void main(void){

char prods[5][27] = {"TV327 31 inch Television", "CD257 CD Player", "TA677 Answering Machine", "CS109 Car Stereo", "PC955 Personal Computer"};char lookUp[27], *strPtr = NULL;int index;

Page 24: Chapter 10 – Characters, Strings, and the  string  Class

24

Starting Out with C++, 3rd Edition

Program continuescout << "\tProduct Database\n\n";cout << "Enter a product number to search for: ";cin.getline(lookUp, 27);for (index = 0; index < 5; index++){

strPtr = strstr(prods[index], lookUp);if (strPtr != NULL)break;

}if (strPtr == NULL)

cout << "No matching product was found.\n";else

cout << prods[index] << endl;}

Page 25: Chapter 10 – Characters, Strings, and the  string  Class

25

Starting Out with C++, 3rd Edition

Program Output With Example inputProduct Database

Enter a product to search for: CD257 [Enter]CD257 CD PlayerProgram Output With Example inputProduct Database

Enter a product to search for: CS [Enter]CS109 Car StereoProgram Output With Other Example inputProduct DatabaseEnter a product to search for: AB [Enter]No matching product was found.

Page 26: Chapter 10 – Characters, Strings, and the  string  Class

26

Starting Out with C++, 3rd Edition

10.5 String/Numeric Conversion Functions

• The C++ library provides functions for converting a C-string representation of a number to a numeric data type, and vice-versa.

• The functions in this section require the stdlib.h file to be included.

Page 27: Chapter 10 – Characters, Strings, and the  string  Class

27

Starting Out with C++, 3rd Edition

Table 10-4Function Description

atoi Accepts a C-string as an argument. The function converts the C-string to an integer and returns that value. Example Usage: Num = atoi("4569");

atol Accepts a C-string as an argument. The function converts the C-string to a long integer and returns that value. Example Usage: Lnum = atol("500000");

atof Accepts a C-string as an argument. The function converts the C-string to a float and returns that value. Example Usage: Fnum = atof("3.14159");

Page 28: Chapter 10 – Characters, Strings, and the  string  Class

28

Starting Out with C++, 3rd Edition

Table 10-4 Continued

Function Description

itoa Converts an integer to a C-string. The first argument,

value, is the integer. The result will be stored at the location pointed to by the second argument, string.

The third argument, base, is an integer. It specifies the numbering system that the converted integer should be expressed in. ( 8 = octal, 10 = decimal, 16 = hexadecimal, etc. ) Example Usage: itoa(value, string, base)

Page 29: Chapter 10 – Characters, Strings, and the  string  Class

29

Starting Out with C++, 3rd Edition

Program 10-7// This program demonstrates the strcmp and atoi functions.

#include <iostream.h>#include <string.h> // For strcmp#include <stdlib.h> // For atoi

void main(void){

char input[20];int total = 0, count = 0;float average;

cout << "This program will average a series of numbers.\n";cout << "Enter the first number or Q to quit: ";cin.getline(input, 20);

Page 30: Chapter 10 – Characters, Strings, and the  string  Class

30

Starting Out with C++, 3rd Edition

Program continues while ((strcmp(input, "Q") != 0)&&(strcmp(input, "q") != 0))

{total += atoi(input); // Keep a running totalcount++; // Keep track of how many numbers enteredcout << "Enter the next number or Q to quit: ";cin.getline(input, 20);

}if (count != 0){

average = total / count;cout << "Average: " << average << endl;

}}

Page 31: Chapter 10 – Characters, Strings, and the  string  Class

31

Starting Out with C++, 3rd Edition

Program Output With Example inputThis program will average a series of numbers.Enter the first number or Q to quit: 74 [Enter]Enter the next number or Q to quit: 98 [Enter]Enter the next number or Q to quit: 23 [Enter]Enter the next number or Q to quit: 54 [Enter]Enter the next number or Q to quit: Q [Enter]Average: 62

Page 32: Chapter 10 – Characters, Strings, and the  string  Class

32

Starting Out with C++, 3rd Edition

10.6 Focus on Software Engineering: Writing Your Own C-string-Handling Functions• You can design your own specialized

functions for manipulating C-strings.

Page 33: Chapter 10 – Characters, Strings, and the  string  Class

33

Starting Out with C++, 3rd Edition

Program 10-8// This program uses a function to copy a C-string into an array.

#include <iostream.h>

void stringCopy(char [], char []); // Function prototype

void main(void){

char first[30], second[30];cout << "Enter a string with no more than 29 characters:\n";cin.getline(first, 30);stringCopy(first, second);cout << "The string you entered is:\n" << second << endl;

}

Page 34: Chapter 10 – Characters, Strings, and the  string  Class

34

Starting Out with C++, 3rd Edition

Program continues

// Definition of the stringCopy function.// This function accepts two character arrays as// arguments. The function assumes the two arrays// contain C-strings. The contents of the second array is// copied to the first array.

void stringCopy(char string1[], char string2[]){

int index = 0;while (string1[index] != '\0'){

string2[index] = string1[index];index++;

}string2[index] = '\0';

}

Page 35: Chapter 10 – Characters, Strings, and the  string  Class

35

Starting Out with C++, 3rd Edition

Program Output With Example inputEnter a string with no more than 29 characters:Thank goodness it’s Friday! [Enter]The string you entered is:Thank goodness it's Friday!

Page 36: Chapter 10 – Characters, Strings, and the  string  Class

36

Starting Out with C++, 3rd Edition

Program 10-9// This program uses the function nameSlice to "cut" the last// name off of a string that contains the user's first and // last names.#include <iostream.h>

void nameSlice(char []); // Function prototype

void main(void){

char name[41];cout << "Enter your first and last names, separated ";cout << "by a space:\n";cin.getline(name, 41);nameSlice(name);cout << "Your first name is: " << name << endl;

}

Page 37: Chapter 10 – Characters, Strings, and the  string  Class

37

Starting Out with C++, 3rd Edition

Program continues

// Definition of function nameSlice. This function accepts a// character array as its argument. It scans the array looking// for a space. When it finds one, it replaces it with a null// terminator.

void nameSlice(char userName[]){

int count = 0;while (userName[count] != ' ' && userName[count] != '\0')count++;if (userName[count] == ' ')userName[count] = '\0';

}

Page 38: Chapter 10 – Characters, Strings, and the  string  Class

38

Starting Out with C++, 3rd Edition

Program Output With Example inputEnter your first and last names, separated by a space:Jimmy Jones [Enter]Your first name is: Jimmy

Page 39: Chapter 10 – Characters, Strings, and the  string  Class

39

Starting Out with C++, 3rd Edition

Figure 10-3

Page 40: Chapter 10 – Characters, Strings, and the  string  Class

40

Starting Out with C++, 3rd Edition

Figure 10-4

Page 41: Chapter 10 – Characters, Strings, and the  string  Class

41

Starting Out with C++, 3rd Edition

Using Pointers to pass C-string arguments

• Very useful• Can assume string exists from address

pointed to by the pointer up to the ‘\0’

Page 42: Chapter 10 – Characters, Strings, and the  string  Class

42

Starting Out with C++, 3rd Edition

Program 10-10

// This program demonstrates a function, countChars, that counts// the number of times a specific character appears in a string.#include <iostream.h>

// Function prototypeint countChars(char *, char);

void main(void){

char userString[51], letter;cout << "Enter a string (up to 50 characters): ";cin.getline(userString, 51);cout << "Enter a character and I will tell you how many\n";cout << "times it appears in the string: ";cin >> letter;cout << letter << " appears ";cout << countChars(userString, letter) << " times.\n";

}

Page 43: Chapter 10 – Characters, Strings, and the  string  Class

43

Starting Out with C++, 3rd Edition

Program continues

// Definition of countChars. The parameter strPtr is a pointer// that points to a string. The parameter ch is a character that// the function searches for in the string. The function returns// the number of times the character appears in the string.

int countChars(char *strPtr, char ch){

int times = 0;while (*strPtr != '\0'){if (*strPtr == ch)times++;strPtr++;}return times;

}

Page 44: Chapter 10 – Characters, Strings, and the  string  Class

44

Starting Out with C++, 3rd Edition

Program Output With Example inputEnter a string (up to 50 characters):Starting Out With

C++ [Enter]Enter a character and I will tell you how manytimes it appears in the string: t [Enter]t appears 4 times.

Page 45: Chapter 10 – Characters, Strings, and the  string  Class

45

Starting Out with C++, 3rd Edition

The C++ string Class• Offers “ease of programming” advantages

over the use of C-strings• Need to #include the string header file

(Notice there is no .h extension.)• Use the following statement after the

#include statements:using namespace std;

Page 46: Chapter 10 – Characters, Strings, and the  string  Class

46

Starting Out with C++, 3rd Edition

Program 10-12// This program demonstrates the C++ string class.#include <iostream>#include <string> // Required for the string classusing namespace std;

void main(void){

string movieTitle;string name("William Smith");

movieTitle = "Wheels of Fury";cout << "My favorite movie is " << movieTitle << endl;

}

Program outputMy favorite movie is Wheels of Fury

Page 47: Chapter 10 – Characters, Strings, and the  string  Class

47

Starting Out with C++, 3rd Edition

A note about the iostream header file

• The preceding program uses the iostream header, not iostream.h.

• With some compilers, you must include the iostream header instead of iostream.h when using cout and cin with string objects.

Page 48: Chapter 10 – Characters, Strings, and the  string  Class

48

Starting Out with C++, 3rd Edition

Program 10-13: Using cin with a string object// This program demonstrates how cin can read a string into// a string class object.

#include <iostream>#include <string>using namespace std;

void main(void){

string name;cout << "What is your name? " << endl;cin >> name;cout << "Good morning " << name << endl;

}

Page 49: Chapter 10 – Characters, Strings, and the  string  Class

49

Starting Out with C++, 3rd Edition

Program Output With Example InputWhat is your name? PeggyGood morning Peggy

Page 50: Chapter 10 – Characters, Strings, and the  string  Class

50

Starting Out with C++, 3rd Edition

Reading a line of input into a string class object

• Use the getline function to read a line of input, with spaces, into a string object. Example code:

string name;cout << “What is your name? “;getline(cin, name);

Page 51: Chapter 10 – Characters, Strings, and the  string  Class

51

Starting Out with C++, 3rd Edition

Comparing and Sorting string Objects

• You may use the relational operators to compare string objects: < > <= >= == !=

Page 52: Chapter 10 – Characters, Strings, and the  string  Class

52

Starting Out with C++, 3rd Edition

Program 10-14// This program uses the == operator to compare the string entered// by the user with the valid stereo part numbers.

#include <iostream>#include <string>using namespace std;

void main(void){

const float aprice = 249.0, bprice = 299.0;string partNum;

cout << "The stereo part numbers are:\n";cout << "\tBoom Box, part number S147-29A\n";cout << "\tShelf Model, part number S147-29B\n";cout << "Enter the part number of the stereo you\n";cout << "wish to purchase: ";cin >> partNum;cout.setf(ios::fixed | ios::showpoint);cout.precision(2);

Page 53: Chapter 10 – Characters, Strings, and the  string  Class

53

Starting Out with C++, 3rd Edition

Program 10-14 (continued)

if (partNum == "S147-29A")cout << "The price is $" << aprice << endl;

else if (partNum == "S147-29B")cout << "The price is $" << bprice << endl;

elsecout << partNum << " is not a valid part number.\n";

}

Program OutputThe stereo part numbers are: Boom Box, part number S147-29A Shelf Model, part number S147-29BEnter the part number of the stereo youwish to purchase: S147-29A [Enter]The price is $249.00

Page 54: Chapter 10 – Characters, Strings, and the  string  Class

54

Starting Out with C++, 3rd Edition

Other Ways to Declare string Objects

Declaration Example Description

string address Declares an empty string object named address.

string name(“Bill Smith”); name is a string object initialized with “Bill Smith”

string person1(person2); person1 is initialized with a copy of person2. person2 may be either a string object or a char array.

See Table 10-8 (page 589) for more examples.

Page 55: Chapter 10 – Characters, Strings, and the  string  Class

55

Starting Out with C++, 3rd Edition

Table 10-10 Other Supported Operators

>> Extracts characters from a stream and inserts them into a string. Characters are copied until a whitespace or the end of the string is encountered.

<< Inserts a string into a stream.

= Assigns the string on the right to the string object on the left.

+= Appends a copy of the string on the right to the string object on the left.

+ Returns a string that is the concatenation of the two string operands.

[] Implements array-subscript notation, as in name[x]. A reference to the character in the x position is returned.

Page 56: Chapter 10 – Characters, Strings, and the  string  Class

56

Starting Out with C++, 3rd Edition

Program 10-17// This program demonstrates the C++ string class.#include <iostream>#include <string>using namespace std;

void main(void){

string str1, str2, str3;str1 = "ABC";str2 = "DEF";str3 = str1 + str2;cout << str1 << endl;cout << str2 << endl;cout << str3 << endl;str3 += "GHI";cout << str3 << endl;

}

Page 57: Chapter 10 – Characters, Strings, and the  string  Class

57

Starting Out with C++, 3rd Edition

Program Output

ABCDEFABCDEFABCDEFGHI

Page 58: Chapter 10 – Characters, Strings, and the  string  Class

58

Starting Out with C++, 3rd Edition

string class member functions

• Many member functions exist.• See Table 10-10 (pages 592-594)