Download presentation
Presentation is loading. Please wait.
Published byJocelyn Park Modified over 9 years ago
1
CS102 Introduction to Computer Programming Chapter 10 Characters and Strings
2
Topics for Discussion Character Testing Character Case Conversion Review of the Internal Storage of Strings Strings Stored in Arrays Library Functions for Working With Arrays String Numeric Conversion Functions Writing String Handling Functions
3
Character Testing In C a macro is a #define that takes arguments –It behaves like a function call –When a macro is called it is inserted directly into the program –Replaced in C++ by the inline function Include the ctype.h header for the following macros: Concept - The C++ Library provides macros for testing characters
4
#include isalphareturns True if a letter of the alphabet isalnumreturns True if a letter or number 0-9 isdigitreturns True if a number 0-9 islowerreturns True if a lower case letter isprintreturns True if a printable character ispunctreturns True if a printable character other than a letter or digit or space isupperreturns True if a uppercase letter isspacereturns True if a white space character –space' ' –newline'\n' –vertical tab'\v ' –tab'\t'
5
Program 10-1 /* This program demonstrates some of the character testing macros. */ #include 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; 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"; } Program Output 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 Enter any character: 7 [Enter] The character you entered is: 7 Its ASCII code is: 55 That's a numeric digit.
6
Program 10-2 /* This program tests a customer number to determine if it is in the proper format.*/ #include // Function prototype int 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); if (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"; }
7
Program 10-2 // Definition of function TestNum. int TestNum(char CustNum[]) { // Test the first three characters for letters for (int Count = 0; Count < 3; Count++) { if (!isalpha(CustNum[Count])) return 0; } // Test the last 4 characters for numeric digits for (int Count = 3; Count < 7; Count++) { if (!isdigit(CustNum[Count])) return 0; } return 1; } Program Output 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
8
Character Case Conversion Touppper (tolower) –accepts a single character as an argument –if the character is lower case(upper case) it returns the upper case(lower case) equivalent –if is already upper case(lower case) or not a letter the original value is returned Call by value. The argument is not changed Must include ctype.h Concept - The C++ Library provides functions for converting a character to upper or lower case.
9
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 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); 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'); }
10
Program 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]
11
Internal Storage of Strings Review The null character '\0' is used to terminate a character string A string constant is any literal string enclosed in " " –it has its own storage location just like the variables of an array A string stored in an array can be processed using standard subscript notation. Concept - In C++, a string is a sequence of characters stored in consecutive memory locations, terminated by a null character.
12
Program 10-5 /* This program cycles through a character array, displaying each element until a null terminator is encountered.*/ #include 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++; } Program Output 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!
13
String Manipulators Review cin can be used to input a character string with no white space characters cin >>last_name; Edwards cin.getline can be used input a character string with spaces into an array cin.getline(name,20); Daniel Edwards cin.get can be use to input a single character of any type cin.get(ch); Enter
14
Strings Stored in Arrays There is no data type for string variables. –Character strings can be stored in character arrays There is no boundary checking for Strings. –Be sure the array is large enough to hold the null terminator An array name with no [ ] and subscripts is the address of the first element of the array. array = = &array[0] is true A string stored in an array can be processed using standard subscript notation.
15
Library Functions for Working With Character Arrays strlenreturns the length of a string not including the null terminator int len; char Name[] ="Francis"; len = strlen (Name); cout << len; 7 strcatappends the contents of one string to another char First[13] ="Francis", Second [] = "Bacon" ; strcat (First, Second); cout <<First <<" "<<Second;FrancisBacon Bacon strcpycopies one string to another char First[14] = "Francis", Name [] = "Francis Bacon" strcpy (First, Name) cout <<First <<" " <<Name;Francis Bacon Francis Bacon
16
Library Functions for Working With Character Arrays strncpycopies a specified number of characters from string2 to string1 char First [8], Name[] = "Francis Bacon"; strncpy (first, Name, 7); cout << First <<" " <<Name;Francis Francis Bacon strcmpcompares the contents of two strings. returns 0 if string2 = = string1 returns negative if string2 is > string 1 returns positive if string2 is < string 1 strstrsearches a string for the location of another string char Name[] = "Francis Bacon", Second[] = "Bacon" ; cout <<strstr (Name, Second);Bacon (because cout displays the string if given an address)
17
Program 10-6 // This program uses the strstr function to search an array of strings for a name.*/ #include #include // 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; cout << "\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; }
18
Program Output 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.
19
Differences Between Strings and Numbers There is a difference between numbers stored as strings and numbers stored as numeric values. –A character string of digits isn't a number but a series of ASCII codes. mathematical operations can not be performed on it –It uses 1 byte of memory for each digit. an int data type takes 2 bytes for the whole number The C++ library provides functions for converting a string representation of a number to a numeric data type and vice- versa.
20
10.5 String/Numeric Conversion Functions The C++ library provides functions for converting a string representation of a number to a numeric data type, and vice- versa. The functions in this section require the stdlib file to be included.
21
String Numeric Conversion Functions atoiconverts a string of digits into an integer. atolconverts a string of digits into a long integer. atofconverts a string of digits into a floating point number. itoaconverts an integer into a character string and stores it in an array. Caution: make sure the array is large enough to hold all the characters plus the null terminator.
22
Program 10-7 // This program demonstrates the strcmp and atoi functions. #include #include // For strcmp #include // 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); 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 << "Enter the next number or Q to quit: "; cin.getline(Input, 20); } if (Count != 0) { Average = Total / Count; cout << "Average: " << Average << endl; }
23
Program Output 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
24
The C++ string Class Offers “ease of programming” advantages over the use of C-strings Need to #include the string header file
25
Program 10-12 // This program demonstrates the C++ string class. #include #include // Required for the string class using namespace std; void main(void) { string movieTitle; string name("William Smith"); movieTitle = "Wheels of Fury"; cout << "My favorite movie is " << movieTitle << endl; } Program output My favorite movie is Wheels of Fury
26
Program 10-13: Using cin with a string object // This program demonstrates how cin can read a string into // a string class object. #include using namespace std; void main(void) { string name; cout << "What is your name? " << endl; cin >> name; cout << "Good morning " << name << endl; }
27
Program Output With Example Input What is your name? Peggy Good morning Peggy
28
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);
29
Comparing and Sorting string Objects You may use the relational operators to compare string objects: = == !=
30
Program 10-14 // This program uses the == operator to compare the string entered // by the user with the valid stereo part numbers. #include #include using namespace std; void main(void) { const float aprice = 249.0, bprice = 299.0; string partNum; cout > partNum; cout << fixed << showpoint << precision(2);
31
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; else cout << partNum << " 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-29B Enter the part number of the stereo you wish to purchase: S147-29A [Enter] The price is $249.00
32
Other Ways to Declare string Objects Declaration ExampleDescription 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.
33
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.
34
Program 10-17 // This program demonstrates the C++ string class. #include 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; }
35
Program Output ABC DEF ABCDEF ABCDEFGHI
36
string class member functions Many member functions exist. See Table 10-10 (pages 592-594)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.