Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 1400 Chapter 10 Strings. Character testing library #include bool isalpha (char c); bool isalnum (char c); bool isdigit (char c); bool islower (char.

Similar presentations


Presentation on theme: "CS 1400 Chapter 10 Strings. Character testing library #include bool isalpha (char c); bool isalnum (char c); bool isdigit (char c); bool islower (char."— Presentation transcript:

1 CS 1400 Chapter 10 Strings

2 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);

3 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”;

4 Character conversion library #include char toupper (char c); char tolower (char c);

5 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]); }

6 C-String library functions #include int strlen (char str[ ]); void strcpy (char dest[ ], char src[ ]); int strcmp (char src1[ ], char src2[ ]); FYI void strcat (char dest[ ], char src[ ]); void strncpy (char dest[ ], char src[ ], int count); char* strstr (char str[ ], char search[ ]);

7 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.”;

8 String-to-Number conversions #include int atoi (char word[ ]); int atol (char word[ ]); float atof (char word[ ]); Note: itoa() has been deprecated under Microsoft Visual Studio.NET.

9 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

10 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…

11 sprintf() examples… char line[80]; int x = 1234; float y = 3.14159; 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: $ 3.14159 cost rounded: $ 3.14

12 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

13 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 1-800-CHEATEM. We look forward to taking you on this trip, Bogus Travel and Condo Sales

14 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 1-800-CHEATEM. We look forward to taking you on this trip, Bogus Travel and Condo Sales

15 Manipulating strings There are several ways of manipulating textual strings; –C-strings strings are stored in arrays of characters –C++ string objects strings are stored in an abstract data type –CString objects strings are stored in an abstract data type specific to Microsoft GUIs. –etc…..

16 The C++ string class A class is an abstract data type -- 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”);

17 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 just 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”;

18 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)

19 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;

20 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…)

21 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…

22 Conversions… A C-string or literal can be assigned to a string char name[5] = “Fred”; string othername; othername = name; But a string cannot be assigned to a C- string name = othername;

23 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).

24 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

25 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

26 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; }

27 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]); }

28 Input for strings… ifstream fin; string string_a, string_b, string_c; char c; … fin >> string_a; // input the next word getline (fin, string_b); // input next line while (fin.get(c)) string_c += c; // input to end of file

29 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”

30 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

31 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: 23456789.01234 With 6% added: $24,864,196.35 strings.cpp


Download ppt "CS 1400 Chapter 10 Strings. Character testing library #include bool isalpha (char c); bool isalnum (char c); bool isdigit (char c); bool islower (char."

Similar presentations


Ads by Google