Title: Chapter 10
1Chapter 10 Characters, Strings, and the string
Class
210.1 Character Testing
- The C library provides several macros for
testing characters. - Be sure to include ctype.h header file
3Table 10-1
4Program 10-1
- // This program demonstrates some of the
character testing - // functions.
- include ltiostream.hgt
- include ltctype.hgt
- void main(void)
-
- char input
- cout ltlt "Enter any character "
- cin.get(input)
- cout ltlt "The character you entered is " ltlt
input ltlt endl - cout ltlt "Its ASCII code is " ltlt int(input) ltlt
endl
5Program continues
- if (isalpha(input))
- cout ltlt "That's an alphabetic character.\n"
- if (isdigit(input))
- cout ltlt "That's a numeric digit.\n"
- if (islower(input))
- cout ltlt "The letter you entered is
lowercase.\n" - if (isupper(input))
- cout ltlt "The letter you entered is
uppercase.\n" - if (isspace(input))
- cout ltlt "That's a whitespace character.\n"
-
6Program Output With Example input
- Enter any character A Enter
- The character you entered is A
- Its ASCII code is 65
- That's an alphabetic character.
- The letter you entered is uppercase.
- Program Output With Other Example input
- Enter any character 7 Enter
- The character you entered is 7
- Its ASCII code is 55
- That's a numeric digit.
7Program 10-2
- // This program tests a customer number to
determine if it is - // in the proper format.
- include ltiostream.hgt
- include ltctype.hgt
- // Function prototype
- bool testNum(char )
- void main(void)
-
- char customer8
- cout ltlt "Enter a customer number in the form "
- cout ltlt "LLLNNNN\n"
- cout ltlt "(LLL letters and NNNN numbers) "
- cin.getline(customer, 8)
8Program continues
- if (testNum(customer))
- cout ltlt "That's a valid customer number.\n"
- else
-
- cout ltlt "That is not the proper format of the
" - cout ltlt "customer number.\nHere is an
example\n" - cout ltlt " ABC1234\n"
-
-
- // Definition of function testNum.
- bool testNum(char custNum)
-
- // Test the first three characters for
alphabetic letters - for (int count 0 count lt 3 count)
-
9Program continues
- if (!isalpha(custNumcount))
- return false
-
- // Test the last 4 characters for numeric digits
- for (int count 3 count lt 7 count)
-
- if (!isdigit(custNumcount))
- return false
-
- return true
-
-
10Program Output With Example input
- Enter 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 input
- Enter 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
1110.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
12Table 10-2
13Program 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 ltiostream.hgt
- include ltctype.hgt
- void main(void)
-
- const float pi 3.14159
- float radius
- char go
- cout ltlt "This program calculates the area of a
circle.\n" - cout.precision(2)
- cout.setf(iosfixed)
14Program continues
- do
-
- cout ltlt "Enter the circle's radius "
- cin gtgt radius
- cout ltlt "The area is " ltlt (pi radius
radius) - cout ltlt endl
- do
-
- cout ltlt "Calculate another? (Y or N) "
- cin gtgt go
- while (toupper(go) ! 'Y' toupper(go) !
'N') - while (toupper(go) 'Y')
-
15Program Output With Example input
- This program calculates the area of a circle.
- Enter the circle's radius 10 Enter
- The area is 314.16
- Calculate another? (Y or N) b Enter
- Calculate another? (Y or N) y Enter
- Enter the circle's radius 1 Enter
- The area is 3.14
- Calculate another? (Y or N) n Enter
1610.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
17Program 10-4
- // This program contains string constants
- include ltiostream.hgt
- void main(void)
-
- char again
- do
-
- cout ltlt "C programming is great fun!" ltlt
endl - cout ltlt "Do you want to see the message again?
" - cin gtgt again
- while (again 'Y' again 'y')
18Program 10-5
- // This program cycles through a character array,
displaying - // each element until a null terminator is
encountered. - include ltiostream.hgt
- void main(void)
-
- char line80
- int count 0
- cout ltlt "Enter a sentence of no more than 79
characters\n" - cin.getline(line, 80)
- cout ltlt "The sentence you entered is\n"
- while (linecount ! '\0')
-
- cout ltlt linecount
- count
-
-
19Program Output with Example input
- Enter a sentence of no more than 79 characters
- C is challenging but fun! Enter
- The sentence you entered is
- C is challenging but fun!
2010.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
21Figure 10-2
22Table 10-3
23Program 10-6
- // This program uses the strstr function to
search an array - // of strings for a name.
- include ltiostream.hgt
- include ltstring.hgt // For strstr
- void main(void)
-
- char prods527 "TV327 31 inch
Television", - "CD257 CD Player",
- "TA677 Answering Machine",
- "CS109 Car Stereo",
- "PC955 Personal
Computer" - char lookUp27, strPtr NULL
- int index
24Program continues
- cout ltlt "\tProduct Database\n\n"
- cout ltlt "Enter a product number to search for
" - cin.getline(lookUp, 27)
- for (index 0 index lt 5 index)
-
- strPtr strstr(prodsindex, lookUp)
- if (strPtr ! NULL)
- break
-
- if (strPtr NULL)
- cout ltlt "No matching product was found.\n"
- else
- cout ltlt prodsindex ltlt endl
-
25Program Output With Example input
- Product Database
- Enter a product to search for CD257 Enter
- CD257 CD Player
- Program Output With Example input
- Product Database
- Enter a product to search for CS Enter
- CS109 Car Stereo
- Program Output With Other Example input
- Product Database
- Enter a product to search for AB Enter
- No matching product was found.
2610.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.
27Table 10-4
28Table 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)
29Program 10-7
- // This program demonstrates the strcmp and atoi
functions. - include ltiostream.hgt
- include ltstring.hgt // For strcmp
- include ltstdlib.hgt // For atoi
- void main(void)
-
- char input20
- int total 0, count 0
- float average
- cout ltlt "This program will average a series of
numbers.\n" - cout ltlt "Enter the first number or Q to quit "
- cin.getline(input, 20)
30Program continues
- while ((strcmp(input, "Q") !
0)(strcmp(input, "q") ! 0)) -
- total atoi(input) // Keep a running total
- count // Keep track of how many numbers
entered - cout ltlt "Enter the next number or Q to quit "
- cin.getline(input, 20)
-
- if (count ! 0)
-
- average total / count
- cout ltlt "Average " ltlt average ltlt endl
-
-
-
31Program Output With Example input
- This 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
3210.6 Focus on Software Engineering Writing
Your Own C-string-Handling Functions
- You can design your own specialized functions for
manipulating C-strings.
33Program 10-8
- // This program uses a function to copy a
C-string into an array. - include ltiostream.hgt
- void stringCopy(char , char ) // Function
prototype - void main(void)
-
- char first30, second30
- cout ltlt "Enter a string with no more than 29
characters\n" - cin.getline(first, 30)
- stringCopy(first, second)
- cout ltlt "The string you entered is\n" ltlt second
ltlt endl
34Program 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 (string1index ! '\0')
-
- string2index string1index
- index
-
- string2index '\0'
-
35Program Output With Example input
- Enter a string with no more than 29 characters
- Thank goodness its Friday! Enter
- The string you entered is
- Thank goodness it's Friday!
36Program 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 ltiostream.hgt
- void nameSlice(char ) // Function prototype
- void main(void)
-
- char name41
- cout ltlt "Enter your first and last names,
separated " - cout ltlt "by a space\n"
- cin.getline(name, 41)
- nameSlice(name)
- cout ltlt "Your first name is " ltlt name ltlt endl
37Program 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 (userNamecount ! ' ' userNamecount
! '\0') - count
- if (userNamecount ' ')
- userNamecount '\0'
-
-
-
38Program Output With Example input
- Enter your first and last names, separated by a
space - Jimmy Jones Enter
- Your first name is Jimmy
39Figure 10-3
40Figure 10-4
41Using Pointers to pass C-string arguments
- Very useful
- Can assume string exists from address pointed to
by the pointer up to the \0
42Program 10-10
- // This program demonstrates a function,
countChars, that counts - // the number of times a specific character
appears in a string. - include ltiostream.hgt
- // Function prototype
- int countChars(char , char)
- void main(void)
-
- char userString51, letter
- cout ltlt "Enter a string (up to 50 characters)
" - cin.getline(userString, 51)
- cout ltlt "Enter a character and I will tell you
how many\n" - cout ltlt "times it appears in the string "
- cin gtgt letter
- cout ltlt letter ltlt " appears "
- cout ltlt countChars(userString, letter) ltlt "
times.\n"
43Program 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
-
-
44Program Output With Example input
- Enter a string (up to 50 characters)Starting Out
With C Enter - Enter a character and I will tell you how many
- times it appears in the string t Enter
- t appears 4 times.
45The 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
46Program 10-12
- // This program demonstrates the C string
class. - include ltiostreamgt
- include ltstringgt // Required for the string
class - using namespace std
- void main(void)
-
- string movieTitle
- string name("William Smith")
- movieTitle "Wheels of Fury"
- cout ltlt "My favorite movie is " ltlt movieTitle ltlt
endl -
-
- Program output
- My favorite movie is Wheels of Fury
47A 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.
48Program 10-13 Using cin with a string object
- // This program demonstrates how cin can read a
string into - // a string class object.
- include ltiostreamgt
- include ltstringgt
- using namespace std
- void main(void)
-
- string name
- cout ltlt "What is your name? " ltlt endl
- cin gtgt name
- cout ltlt "Good morning " ltlt name ltlt endl
49Program Output With Example Input
What is your name? Peggy Good morning Peggy
50Reading 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
codestring namecout ltlt What is your name?
getline(cin, name)
51Comparing and Sorting string Objects
- You may use the relational operators to compare
string objects - lt gt lt gt !
52Program 10-14
// This program uses the operator to compare
the string entered// by the user with the valid
stereo part numbers.include ltiostreamgtinclude
ltstringgtusing namespace stdvoid
main(void) const float aprice 249.0, bprice
299.0 string partNum cout ltlt "The stereo
part numbers are\n" cout ltlt "\tBoom Box, part
number S147-29A\n" cout ltlt "\tShelf Model, part
number S147-29B\n" cout ltlt "Enter the part
number of the stereo you\n" cout ltlt "wish to
purchase " cin gtgt partNum cout.setf(iosfix
ed iosshowpoint) cout.precision(2)
53Program 10-14 (continued)
if (partNum "S147-29A") cout ltlt "The price
is " ltlt aprice ltlt endl else if (partNum
"S147-29B") cout ltlt "The price is " ltlt bprice
ltlt endl else cout ltlt partNum ltlt " is not a
valid part number.\n" Program Output The
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 EnterThe price
is 249.00
54Other 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.
55Table 10-10 Other Supported Operators
gtgt 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.
ltlt 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 namex. A reference to the character in the x position is returned.
56Program 10-17
- // This program demonstrates the C string
class. - include ltiostreamgt
- include ltstringgt
- using namespace std
- void main(void)
-
- string str1, str2, str3
- str1 "ABC"
- str2 "DEF"
- str3 str1 str2
- cout ltlt str1 ltlt endl
- cout ltlt str2 ltlt endl
- cout ltlt str3 ltlt endl
- str3 "GHI"
- cout ltlt str3 ltlt endl
-
57Program Output
58string class member functions
- Many member functions exist.
- See Table 10-10 (pages 592-594)