1 / 48

Starting Out with C++: Early Objects 5 th Edition

Starting Out with C++: Early Objects 5 th Edition. Chapter 12 More About Characters, Strings, and the string Class. Topics. 12.1 C-Strings 12.2 Library Functions for Working with C-Strings 12.3 String/Numeric Conversion Functions 12.4 Character Testing. Topics (continued).

zenda
Download Presentation

Starting Out with C++: Early Objects 5 th Edition

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Starting Out with C++: Early Objects 5th Edition Chapter 12 More About Characters, Strings, and the string Class Starting Out with C++: Early Objects 5/e

  2. Topics 12.1 C-Strings 12.2 Library Functions for Working with C-Strings 12.3 String/Numeric Conversion Functions 12.4 Character Testing © 2006 Pearson Education. All Rights Reserved

  3. Topics (continued) 12.5 Character Case Conversion 12.6 Writing Your Own C-String Handling Functions 12.7 More About the C++ string Class 12.8 Creating Your Own String Class © 2006 Pearson Education. All Rights Reserved

  4. 12.1 C-Strings • C-string: sequence of characters stored in adjacent memory locations and terminated by NULL character • The C-string "Hi there!" would be stored in memory as shown: r e ! H i t h e \0 © 2006 Pearson Education. All Rights Reserved

  5. Why C-Strings? • The STL string object provides all the C-string capabilities, and more, • PLUS safety against bounds violations. • BUT – STL strings not provided in C. • AND – C-strings are more efficient. © 2006 Pearson Education. All Rights Reserved

  6. Microsoft CString • The Microsoft Visual Studio compiler library supports a CString class • Similar to STL string • Used extensively in the MFC libraries • Only available in VS • Conversion between string and CString is easy. © 2006 Pearson Education. All Rights Reserved

  7. Representation of C-strings • As a string literal "Hi There!" • As a pointer to char char *p; • As an array of characters char str[20]; • All three representations are pointers to char © 2006 Pearson Education. All Rights Reserved

  8. String Literals • A string literal is stored as a null-terminated array of char • Compiler uses the address of the array as the value of the string • String literal is a pointer to char value of “hi” is address of this array © 2006 Pearson Education. All Rights Reserved

  9. Array of char • Array of char can be defined and initialized to a C-string char str1[20] = "hi"; • Array of char can be defined and later have a string copied into it char str2[20]; strcpy(str2, "hi"); © 2006 Pearson Education. All Rights Reserved

  10. Array of char • Name of array of char is used as a pointer to char • Unlike string literal, a C-string defined as an array can be referred to in other parts of the program by using the array name © 2006 Pearson Education. All Rights Reserved

  11. Wrong Initialization • DO NOT initialize a C-string this way: char name[]= {'B','i','l','l'}; • Does not supply the terminating NULL character '\0'. • Nothing wrong with this array, but none of the C-string functions will work properly with it. • THIS is a proper C-string: char name[]= {'B','i','l','l',0}; © 2006 Pearson Education. All Rights Reserved

  12. Pointer to char • Defined as char *pStr; • Does not itself allocate memory • Useful in repeatedly referring to C-strings defined as a string literal pStr = "Hi there"; cout << pStr << " " << pStr; © 2006 Pearson Education. All Rights Reserved

  13. Constructing a C-string char *str= 0; int length; cin >> length; // should be >= 0 str= new char[length+1]; for (k= 0; k< length; ++k) str[k]= '*'; str[k]= 0; cout << str << endl; // ***** ... delete[] str; © 2006 Pearson Education. All Rights Reserved

  14. Pointer to char • Pointer to char can also refer to C-strings defined as arrays of char char str[20] = "hi"; char *pStr = str; cout << pStr; // prints hi • Make sure the pointer points to legitimate memory before using it! © 2006 Pearson Education. All Rights Reserved

  15. Constructing a C-string char *str= 0, *ps; // using a pointer int length; cin >> length; // should be >= 0 ps= str= new char[length+1]; for (k= 0; k< length; ++k) *ps++ = '*'; // * first, then ++ *ps= 0; cout << str << endl; // ***** ... delete[] str; © 2006 Pearson Education. All Rights Reserved

  16. 12.2 Library Functions for Working with C-Strings • Require cstring header file • Functions take one or more C-strings as arguments. Argument can be: • Name of an array of char • pointer to char • literal string © 2006 Pearson Education. All Rights Reserved

  17. Library Functions for Working with C-Strings • int strlen(char *str) Returns length of a C-string: cout << strlen("hello"); Prints 5 © 2006 Pearson Education. All Rights Reserved

  18. strcpy • strcpy(char *dest, char *source) Copies a string from a source address to a destination address char name[15]; strcpy(name, "Deborah"); cout << name; // prints Deborah © 2006 Pearson Education. All Rights Reserved

  19. strcmp intstrcmp(char*str1,char*str2) Compares strings stored at two addresses to determine their relative alphabetic order: Returns a value: less than 0 if str1 precedes str2 equal to 0 if str1 equals str2 greater than 0 if str1 succeeds str2 • "Bill" < "BillBarrett" • Uses ASCII character sequence © 2006 Pearson Education. All Rights Reserved

  20. strcmp • Often used to test for equality if(strcmp(str1, str2) == 0) cout << "equal"; else cout << "not equal"; • Also used to determine ordering of C-strings in sorting applications • Note that C-strings cannot be compared using == (compares addresses of C-strings, not contents) © 2006 Pearson Education. All Rights Reserved

  21. strstr • char*strstr(char*str1,char*str2) Searches for the occurrence of str2 within str1. Returns a pointer to the occurrence of str2 within str1 if found, and returns NULL otherwise char s[15] = "Abracadabra"; char *found = strstr(s,"dab"); cout << found; // prints dabra © 2006 Pearson Education. All Rights Reserved

  22. Length-bounded functions • These stop at n characters or the string length, whichever is smaller void strncpy(char* s1, char* s2, int n); int strncmp(char* s1, char* s2, int n); © 2006 Pearson Education. All Rights Reserved

  23. 12.3 String/Numeric Conversion Functions • These functions convert between string and numeric forms of numbers • Need to include the cstdlib header file © 2006 Pearson Education. All Rights Reserved

  24. atoi and atol • atoi converts alphanumeric toint • atol converts alphanumeric tolong • int atoi(char *numericStr) long atol(char *numericStr) • Examples: int number; long lnumber; number = atoi("57"); lnumber = atol("50000"); • Return 0 if not a number © 2006 Pearson Education. All Rights Reserved

  25. atof • atof converts a numeric string to a floating point number, actually a double • double atof(char *numericStr) • Example: double dnumber; dnumber = atof("3.14159"); • Returns 0.0 if not a number © 2006 Pearson Education. All Rights Reserved

  26. atoi, atol, atof • if C-string being converted contains non-digits, results are undefined • function may return result of conversion up to first non-digit • function may return 0 © 2006 Pearson Education. All Rights Reserved

  27. itoa • itoa converts an int to an alphanumeric string • Allows user to specify the base of conversion itoa(int num,char*numStr,int base) • num : number to convert • numStr: array to hold resulting string • make sure it's large enough! • base: base of conversion © 2006 Pearson Education. All Rights Reserved

  28. itoa itoa(int num,char*numStr,int base) • Example: To convert the number 1200 to a hexadecimal string char numStr[10]; itoa(1200, numStr, 16); • The function performs no bounds-checking on the array numStr – make sure it's large enough! © 2006 Pearson Education. All Rights Reserved

  29. sprintf, sscanf • Too complicated to describe here • sprintf uses a format string to write a string target containing various other types • sscanf uses a format string to read a string target containing various other types © 2006 Pearson Education. All Rights Reserved

  30. 12.4 Character Testing • require cctype header file © 2006 Pearson Education. All Rights Reserved

  31. Character Testing • require cctype header file © 2006 Pearson Education. All Rights Reserved

  32. Character Testing • require cctype header file © 2006 Pearson Education. All Rights Reserved

  33. 12.5 Character Case Conversion • require cctype header file • Functions: • toupper: convert a letter to uppercase equivalent • tolower: convert a letter to lowercase equivalent © 2006 Pearson Education. All Rights Reserved

  34. toupper toupper: if char argument is lowercase letter, return uppercase equivalent; otherwise, return input unchanged toupper actually takes an integer parameter and returns an integer result. The integers are the ASCII codes of the characters © 2006 Pearson Education. All Rights Reserved

  35. toupper The function charupCase(int i) {return toupper(i);} will work as follows: char greeting[] = "Hello!"; cout << upCase[0];//displays 'H' cout << upCase[1];//displays 'E' cout << upCase[5]; //displays '!' © 2006 Pearson Education. All Rights Reserved

  36. tolower tolower: if int argument is uppercase letter, return lowercase equivalent; otherwise, return input unchanged © 2006 Pearson Education. All Rights Reserved

  37. tolower The function charloCase(int i) {return tolower(i);} will work as follows char greeting[] = "Hello!"; cout << loCase[0]; //displays 'h' cout << loCase[1]; //displays 'e' cout << loCase[5]; //displays '!' © 2006 Pearson Education. All Rights Reserved

  38. 12.6 Writing Your Own C-String Handling Functions • When writing C-String Handling Functions: • can pass char arrays or pointer-to-char • Can perform bounds checking to ensure enough space for results • Can anticipate unexpected user input © 2006 Pearson Education. All Rights Reserved

  39. toLower for a C-string void toLower(char *str) { while (*str) { *str= tolower(*str); str++; } } © 2006 Pearson Education. All Rights Reserved

  40. 12.7 More About the C++ string Class • The string class offers many advantages over C-style strings: • large body of member functions • overloaded operators to simplify expressions • initially empty, "" • more safety with respect to bounds violations • Need to include the string header file © 2006 Pearson Education. All Rights Reserved

  41. string class constructors • Default constructor string() • Copy constructor string(string&) • initializes string object with value of another string object • Convert constructor string(char *) • allows C-strings to be used wherever string class objects are expected • Various other constructors © 2006 Pearson Education. All Rights Reserved

  42. Overloaded string Operators © 2006 Pearson Education. All Rights Reserved

  43. Overloaded string Operators (continued) © 2006 Pearson Education. All Rights Reserved

  44. Overloaded string Operators string word1, phrase; // initially "" string word2 = " Dog"; cin >> word1; // user enters "Hot" // word1 has "Hot" phrase = word1 + word2; // phrase has // "Hot Dog" phrase += " on a bun"; for (int i = 0; i < phrase.length(); i++) cout << phrase[i]; // displays // "Hot Dog on a bun" © 2006 Pearson Education. All Rights Reserved

  45. string Member Functions Categories: • conversion to C-strings: c_str, data • modification: append, assign, clear, copy,erase,insert,replace,swap • space management: capacity,empty,length,resize,size • substrings: find,substr • comparison: compare © 2006 Pearson Education. All Rights Reserved

  46. Conversion to C-strings • data() and c_str() both return the C-string equivalent of a string object • Useful in using a string object with a function that is expecting a C-string char greeting[20] = "Have a "; string str("nice day"); strcat(greeting, str.data()); © 2006 Pearson Education. All Rights Reserved

  47. Modification of string objects • str.append(string s) appends contents of s to end of str str += s; // same as... • Convert constructor for string allows a C-string to be passed in place of s string str("Have a "); str.append("nice day"); • append is overloaded for flexibility © 2006 Pearson Education. All Rights Reserved

  48. Modification of string objects • str.insert(int pos, string s) inserts s at position pos in str • Convert constructor for string allows a C-string to be passed in place of s string str("Have a day"); str.insert(7, "nice "); // str is now "Have a nice day" • insert is overloaded for flexibility © 2006 Pearson Education. All Rights Reserved

More Related