Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 17: Characters, Strings, and the string class Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.

Similar presentations


Presentation on theme: "Lecture 17: Characters, Strings, and the string class Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220."— Presentation transcript:

1 Lecture 17: Characters, Strings, and the string class Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220

2 Character Testing Concept: The C++ library provides several functions for testing characters. To use these functions you must include the cctype header file. Functions return true if the argument matches their test, else return 0 isalpha() isalnum() isdigit() islower() ispring() ispunct() isupper() isspace()

3 // This program tests a customer number to determine whether // it is in the proper format. #include using namespace std; // Function prototype bool testNum(char [], int); int main() { const int SIZE = 8; // Array size char customer[SIZE]; // To hold a customer number // Get the customer number. cout << "Enter a customer number in the form "; cout << "LLLNNNN\n"; cout << "(LLL = letters and NNNN = numbers): "; cin.getline(customer, SIZE); // Determine whether it is valid. if (testNum(customer, SIZE)) 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"; } return 0; } //********************************************************** // Definition of function testNum. * // This function determines whether the custNum parameter * // holds a valid customer number. The size parameter is * // the size of the custNum array. * //********************************************************** bool testNum(char custNum[], int size) { int count; // Loop counter // Test the first three characters for alphabetic letters. for (count = 0; count < 3; count++) { if (!isalpha(custNum[count])) return false; } // Test the remaining characters for numeric digits. for (count = 3; count < size - 1; count++) { if (!isdigit(custNum[count])) return false; } return true; } // This program demonstrates some character testing functions. #include using namespace std; int main() { char input; cout << "Enter any character: "; cin.get(input); cout << "The character you entered is: " << 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"; return 0; }

4 Character Case Conversion Concept: The C++ library offers functions for converting a character to upper or lower case toupper() tolower()

5 // 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 using namespace std; int main() { const double PI = 3.14159; // Constant for Pi double radius; // The circle's radius char goAgain; // To hold Y or N cout << "This program calculates the area of a circle.\n"; cout << fixed << setprecision(2); do { // Get the radius and display the area. cout << "Enter the circle's radius: "; cin >> radius; cout << "The area is " << (PI * radius * radius); cout << endl; // Does the user want to do this again? cout << "Calculate another? (Y or N) "; cin >> goAgain; // Validate the input. while (toupper(goAgain) != 'Y' && toupper(goAgain) != 'N') { cout << "Please enter Y or N: "; cin >> goAgain; } } while (toupper(goAgain) == 'Y'); return 0; }

6 Library functions for working with C-Strings Concept: The C++ library has numerous functions for handling C-strings. These functions perform various tests and manipulations, and require that the cstring header file be included. Must pass one or more C-strings as arguments name of the array string literal

7 NameDescriptionUsageNotes: strlenAccepts a c-string or a pointer to a c-string as an argument. returns the length of the c-string len = strlen(name); strcatAccepts two c-strings or pointers to two c-strings as arguments. The function appends the contents of the second string to the first c-string. The first is altered, the second is left unchanged. strcat(string1,string2);If the array holding the first string isn’t large enough to hold both strings, strcat will overflow the boundaries of the array strcpyAccepts two c-strings or pointer to two c-strings as arguments. The function copies the second c-string to the first c-string. The second is left unchanged. strcpy(string1,string2);Performs no bounds checking. The array specified by the first argument will be overflowed if it isn’t large enough to hold the string specified by the second argument strncatAccepts two c-strings or pointers to two c-strings, and an integer argument. The third argument, an integer, indicates the maximum number of characters to concatenate from the second c-string to the first c-string strncat(string1, string2, n); strncpyAccepts two c-strings or pointers to two c-strings, and an integer argument. The third argument, an integer, indicates the maximum number of characters to copy from the second c- string to the first c-string. If n is less than the length of string2, the null terminator is not automatically appended to string1. If n is greater than the length of string2, string1 is padded with ‘/0’ characters. strncpy(string1, string2, n); strcmpAccepts two c-strings or pointers to two c-strings. If string1 and string2 are the same, returns 0. If string2 is alphabetically greater than string1, returns a negative. Else, returns a positive. if(strcmp(string1, string2); strstrAccepts two c-strings or pointers to two c-strings. 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 (address 0) cout << strstr(string1,string2);

8 // This program uses the strstr function to search an array. #include #include // For strstr using namespace std; int main() { // Constants for array lengths const int NUM_PRODS = 5; // Number of products const int LENGTH = 27; // String length // Array of products char products[NUM_PRODS][LENGTH] = { "TV327 31 inch Television", "CD257 CD Player", "TA677 Answering Machine", "CS109 Car Stereo", "PC955 Personal Computer" }; char lookUp[LENGTH]; // To hold user's input char *strPtr = NULL; // To point to the found product int index; // Loop counter // Prompt the usr for a product number. cout << "\tProduct Database\n\n"; cout << "Enter a product number to search for: "; cin.getline(lookUp, LENGTH); // Search the array for a matching substring for (index = 0; index < NUM_PRODS; index++) { strPtr = strstr(products[index], lookUp); if (strPtr != NULL) break; } // If a matching substring was found, display the product info. if (strPtr != NULL) cout << products[index] << endl; else cout << "No matching product was found.\n"; return 0; }

9 String/Numeric Conversion Functions Concept: The C++ library provides functions for converting a string representation of a number to a numeric data type and vice versa. These functions require the cstdlib header file to be included.

10 NameDescriptionUsageNotes: atoiAccepts a c-string as an argument. The function converts the c-string to an integer and returns that value. num = atoi(“4569”); atolAccepts a c-string as an argument. The function converts the c-string to a long integer and returns that value. lnum=atol(“500000”); atofAccepts a c-string as an argument. The function converts the c-string to a double and returns that value. fnum =atof(“3.1459”); itoaConverts an integer to a string. The first argument, value, is the integer. The result will be stored at the location pointed to be the second argument, string. The third argument, base, is an integer. It specifies the numbering system that the converted integer should be express in (8 = octal, 10 = decimal, 16 = hexadecimal, etc.) itoa(value, string, base);Not supported by all compilers. Performs no bounds checking. Make sure the array is large enough to hold the converted number.

11 // This program demonstrates how the getline function can // be used for all of a program's input. #include using namespace std; int main() { const int INPUT_SIZE = 81; // Size of input array const int NAME_SIZE = 30; // Size of name array char input[INPUT_SIZE]; // To hold a line of input char name[NAME_SIZE]; // To hold a name int idNumber; // To hold an ID number. int age; // To hold an age double income; // To hold income // Get the user's ID number. cout << "What is your ID number? "; cin.getline(input, INPUT_SIZE); // Read as a string idNumber = atoi(input); // Convert to int // Get the user's name. No conversion necessary. cout << "What is your name? "; cin.getline(name, NAME_SIZE); // Get the user's age. cout << "How old are you? "; cin.getline(input, INPUT_SIZE); // Read as a string age = atoi(input); // Convert to int // Get the user's income. cout << "What is your annual income? "; cin.getline(input, INPUT_SIZE); // Read as a string income = atof(input); // Convert to double // Show the resulting data. cout << setprecision(2) << fixed << showpoint; cout << "Your name is " << name <<", you are " << age << " years old,\nand you make $" << income << " per year.\n"; return 0; } // This program demonstrates the strcmp and atoi functions. #include #include // For tolower #include // For strcmp #include // For atoi using namespace std; int main() { const int SIZE = 20; // Array size char input[SIZE]; // To hold user input int total = 0; // Accumulator int count = 0; // Loop counter double average; // To hold the average of numbers // Get the first number. cout << "This program will average a series of numbers.\n"; cout << "Enter the first number or Q to quit: "; cin.getline(input, SIZE); // Process the number and subsequent numbers. while (tolower(input[0]) != 'q') { total += atoi(input); // Keep a running total count++; // Count the numbers entered // Get the next number. cout << "Enter the next number or Q to quit: "; cin.getline(input, SIZE); } // If any numbers were entered, display their average. if (count != 0) { average = static_cast (total) / count; cout << "Average: " << average << endl; } return 0; }

12 The C++ string Class Concept: Standard C++ provides a special data type for storing and working with strings The string class is an abstract data type, which means that it is not one of the primitive, built in data types like char or int #include string movieTitle; movieTitle = “Wheels of Fury”; cout << “My favorite movie is” << movieTitle;

13 // This program demonstrates how cin can read a string into // a string class object. #include using namespace std; int main() { string name; cout << "What is your name? "; cin >> name; cout << "Good morning " << name << endl; return 0; } // This program demonstrates the string class. #include #include // Required for the string class. using namespace std; int main() { string movieTitle; movieTitle = "Wheels of Fury"; cout << "My favorite movie is " << movieTitle << endl; return 0; }

14 Things you can do with the string class Reading a line of input into a string object Comparing and sorting strings do not need a function! use, =,== and != relational operators string name; cout<<“What is your name?”; getline(cin,name); string set1 = “ABC”; string set2 = “XYZ”; if (set1 < set2) cout << “set1 is less than set2.\n”;

15 // This program uses relational operators to alphabetically // sort two strings entered by the user. #include using namespace std; int main () { string name1, name2; // Get a name. cout << "Enter a name (last name first): "; getline(cin, name1); // Get another name. cout << "Enter another name: "; getline(cin, name2); // Display them in alphabetical order. cout << "Here are the names sorted alphabetically:\n"; if (name1 < name2) cout << name1 << endl << name2 << endl; else if (name1 > name2) cout << name2 << endl << name1 << endl; else cout << "You entered the same name twice!\n"; return 0; } // This program uses the == operator to compare the string entered // by the user with the valid stereo part numbers. #include using namespace std; int main() { const double APRICE = 249.0; // Price for part A const double BPRICE = 299.0; // Price for part B string partNum; // Part mumber 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 << fixed << showpoint << setprecision(2); 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"; return 0; }

16 Ways of Defining and Supported Operators There are many ways of defining strings see Table 10-5 Many operators are supported when using strings see Table 10-6

17 // This program demonstrates the C++ string class. #include using namespace std; int main () { // Define three string objects. string str1, str2, str3; // Assign values to all three. str1 = "ABC"; str2 = "DEF"; str3 = str1 + str2; // Display all three. cout << str1 << endl; cout << str2 << endl; cout << str3 << endl; // Concatenate a string onto str3 and display it. str3 += "GHI"; cout << str3 << endl; return 0; } // This program initializes a string object. #include using namespace std; int main() { string greeting; string name("William Smith"); greeting = "Hello "; cout << greeting << name << endl; return 0; }

18 string Class member functions The string class has member functions that perform different actions on the object see Table 10-7

19 // This program demonstrates the C++ string class. #include using namespace std; int main() { // Define three string objects. string str1, str2, str3; // Assign values to all three. str1 = "ABC"; str2 = "DEF"; str3 = str1 + str2; // Use subscripts to display str3 one character // at a time. for (int x = 0; x < str3.size(); x++) cout << str3[x]; cout << endl; // Compare str1 with str2. if (str1 < str2) cout << "str1 is less than str2\n"; else cout << "str1 is not less than str2\n"; return 0; } // This program demonstrates a string // object's length member function. #include using namespace std; int main () { string town; cout << "Where do you live? "; cin >> town; cout << "Your town's name has " << town.length() ; cout << " characters\n"; return 0; }

20 Case Study // This program lets the user enter a number. The // dollarFormat function formats the number as // a dollar amount. #include using namespace std; // Function prototype void dollarFormat(string &); int main () { string input; // Get the dollar amount from the user. cout << "Enter a dollar amount in the form nnnnn.nn : "; cin >> input; dollarFormat(input); cout << "Here is the amount formatted:\n"; cout << input << endl; return 0; } //************************************************************ // Definition of the dollarFormat function. This function * // accepts a string reference object, which is assumed to * // to hold a number with a decimal point. The function * // formats the number as a dollar amount with commas and * // a $ symbol. * //************************************************************ void dollarFormat(string &currency) { int dp; dp = currency.find('.'); // Find decimal point if (dp > 3) // Insert commas { for (int x = dp - 3; x > 0; x -= 3) currency.insert(x, ","); } currency.insert(0, "$"); // Insert dollar sign }


Download ppt "Lecture 17: Characters, Strings, and the string class Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220."

Similar presentations


Ads by Google