CS 1400 Apr 18, 2007 Chapter 10 Strings
Character testing library #include bool isalpha (char c); bool isalnum (char c); bool isdigit (char c); bool islower (char c); bool isupper (char c); bool ispunct (char c); bool isprint (char c); bool isspace (char c);
Example… Verify that a password contains at least 5 alpha and 3 numeric characters char password[10]; int numalpha = 0, numdigit = 0; cin >> password; for (int n=0; n<strlen(password); n++) {if (isalpha(password[n])) numalpha++; else if (isdigit(password[n])) numdigit++; } if (numalpha >= 5 && numdigit >= 3) cout << “valid!\n”;
Character conversion library #include char toupper (char c); char tolower (char c);
Example… Convert a C-string to all lower-case void ConvertToLower (char line[ ]) { int len = strlen(line); for (n=0; n<len; n++) if (isupper(line[n])) line[n] = tolower(line[n]); }
C-String library functions #include int strlen (char str[ ]); void strcpy (char dest[ ], char src[ ]); void strcat (char dest[ ], char src[ ]); void strncpy (char dest[ ], char src[ ], int count); char* strstr (char str[ ], char search[ ]);
The NULL pointer… A special pointer value of zero has been defined as NULL. Some functions returning pointers will return NULL on some occasions Ex: char line[80]; cin >> line; if (strstr (line, “Mr.”) == NULL) cout << “this line does not contain Mr.”;
String-to-Number conversions #include int atoi (char word[ ]); int atol (char word[ ]); float atof (char word[ ]); Note: itoa() is not supported under Microsoft Visual Studio.NET.
Number-to-string conversions #include void sprintf (char line[ ], format_literal, var_list); // convert these variables into a C-String –format_literal: a C-string containing a format specifier for each variable to be converted –var_list: a comma-separated list of variables
Format Specifiers for sprintf() %dan integer position %fa float position %sa C-String position %ndan integer position of n columns %n.mfA float position of n columns, rounding to m decimal places any word that doesn’t begin with % is simply inserted as a literal…
sprintf() examples… char line[80]; int x = 1234; float y = ; sprintf (line, “age: %d cost: $ %f”, x, y); cout << line << endl; sprintf (line, “cost rounded: $ %5.2f”, y); cout << line << endl; output age: 1234 cost: $ cost rounded: $ 3.14
C-String example: Write a program to read in a form letter containing occurrences of the word “CUSTOMER”. Next, allow the user to input a person’s name. Now, replace all occurrences of the word “CUSTOMER” with this name and print the letter. formletter.zip
Form letter Dear CUSTOMER: Congratulations! You have won one of the following trips; 7 days in Hawaii, 10 days in San Francisco, or one day in Park City being hounded by a condo salesman. Yes CUSTOMER, this is the dream award of a lifetime! To claim your trip CUSTOMER, just call CHEATEM. We look forward to taking you on this trip, Bogus Travel and Condo Sales
Example execution: Enter a customer name: Fred Dear Fred: Congratulations! You have won one of the following trips; 7 days in Hawaii, 10 days in San Francisco, or one day in Park City being hounded by a condo salesman. Yes Fred, this is the dream award of a lifetime! To claim your trip Fred, just call CHEATEM. We look forward to taking you on this trip, Bogus Travel and Condo Sales
The C++ string class A class is a new programmer-defined data type with its own set of manipulation functions class functions are called using “dot” notation. You’ve seen this before! ifstream fin; fin.open(“myfile.txt”);
The C++ string class #include A C++ string variable can be treated as a simple variable capable of holding a string. A C++ string is not a char array. A C++ string can be assigned and compared with ordinary assignment and comparison operators such as = and <. string word1, word2; word1 = “Hello”; cin >> word2; if (word1 < word2) cout << “less than”;
C++ string class How big is a string variable (how many characters can it hold)? –As big as it needs to be How is this all accomplished? –don’t know and don’t care (at this point)
Concatenation The “+” operator can be used between two strings, but it means concatenation (not addition) string word1 = “Hello “; string word2 = “and Goodbye!”; string line; line = word1 + word2; cout << line << endl;
Accessing individual characters… Individual characters in a string can be accessed using bracket [ ] notation. cout << word1[3]; // output character 3 word1[4] = ‘X’;// replace character 4 While this makes it appear like a string is an array, it is not! In C++, an operator used with a class means anything the designer of that class wants it to. (More on this to come…)
string member functions string line, word; line.append (word);// append word onto line cout << line.length(); // output the length of line line.erase (position, count); // erase count characters beginning at position pos = line.find (search, position); // determine the index position of search in line (beginning at position) line.swap (word); // swap the contents of line and word cout << line.substr (position, count); // output a substring beginning at position for count characters and many many more…
Conversions… A C-string can be assigned to a string char name[ ] = “Fred”; string othername; othername = name; But a string cannot be assigned to a C- string name = othername;
Rule of Thumb… There are many compatibilities between C-strings and strings, but it is best to use one or the other in a program (at this point in your career).
Examples… Output “YES” if an input string contains the word “MONEY” Find and output a dollar-and-cents amount in a string. Erase all the blanks in a string. Capitalize the name “fred” in a string. Replace, with
Sorting strings void SelectionSort (string array[ ], int size) { int smallest_position; for (int n=0; n<size-1; n++) {smallest_position = FindSmallest (array, n, size); Swap (array, n, smallest_position); } If you have a sorting function that works for integer arrays, it will also work for string arrays – just change int to string! sorting.zip
Find_Smallest() int FindSmallest (string array[ ], int start, int size) { int position = start; string smallest = array[start]; for (int k=start+1; k<size; k++) if (array[k] < smallest) { smallest = array[k]; position = k; } return position; }
Swap() void Swap (string array[ ], int j, int k) { string temp; temp = array[j]; array[j] = array[k]; array[k] = temp; } or… void Swap (string array[ ], int j, int k) { array[j].swap(array[k]); }
C++ string example: Write a program to read in a form letter containing occurrences of the word “CUSTOMER”. Next, allow the user to input a person’s name. Now, replace all occurrences of the word “CUSTOMER” with this name and print the letter. stringformletter.zip
Input for strings… string string_a, string_b, string_c; char c; cin >> string_a; // input the next word getline (cin, string_b); // input next line while (cin.get(c)) string_c += c; // input to line of only ctrl-Z
More string member funcs… string s; s.insert (pos, substr); // insert substr at pos s.replace(pos, n, str); // replace n chars at pos with str example: s = “ me”; s.insert(0,”hello”); s.replace(3, 2, “p”); cout << s;// outputs “help me”
Example Write a program to prompt a user to input a value. Next, add 6% and output this result in standard commercial notation (commas and dollar sign, rounded to 2 dec. places) Input a value: With 6% added: $24,864, strings.cpp