Understanding C-Strings and the String Class in C++

c strings and the string class n.w
1 / 41
Embed
Share

Dive into the world of C-strings and the string class in C++, exploring concepts such as NULL character, representations of C-strings, string literals, pointer usage, array initialization, and more. Learn how C-strings are stored and manipulated in memory, and discover the nuances of working with character arrays in C++ programming.

  • C-Strings
  • String Class
  • NULL Character
  • Representation
  • Pointer

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. C-Strings and the string Class

  2. 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 12-2

  3. What is NULL character? The null character is used to indicate the end of a string It can be specified as the character '\0' the int value 0 the named constant NULL 12-3

  4. 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 12-4

  5. String Literals A string literal (string constant) is stored as a null-terminated array of char The compiler uses the address of the first character of the array as the value of the string A string literal is a const pointer to char value of "hi" is the addressof this array h i \0 12-5

  6. const char *p = nullptr, *q = nullptr; p = Hello ; q = World ; cout << p << q << endl; // prints: Hello World cout << p << is stored at << int(p) << endl; cout << q << is stored at << int(q) << endl; // prints: // Hello is stored at 4206692 // World is stored at 4206699 cout << String literal stored at << int( literal ); // prints: // String literal stored at 4206721 12-6

  7. Array of char An array of char can be defined and initialized to a C- string char str1[20] = "hi"; char str2[] = "Hello"; An array of char can be defined and later have a string copied into it using cin.getline char str3[20]; cout << "Enter your name: "; cin.getline(str3, 20); 12-7

  8. const int LENGTH = 80; char line[LENGTH]; cout << Enter a sentence of no more than << LENGTH-1 << characters:\n ; cin.getline(line, LENGTH); cout << The sentence you entered is: \n ; for (int i = 0; line[i] != \0 ; i++) cout << line[i]; 12-8

  9. C-Strings A string literal allocates an array and then uses the address of the array as a pointer to char to actually represent the string. The array used to store the string literal is allocated implicitly by the compiler. 12-9

  10. C-Strings A C-string represented as an array of characters also allocates an array and then uses the address of the array as a pointer to char to actually represent the string. The array used to store the string is allocated explicitly by the programmer. 12-10

  11. C-Strings The third method of representing a C-string uses a pointer to a char to point to a C- string whose storage has already been allocated by one of the other two methods (string literal or an array of characters). 12-11

  12. Pointer to char Defined as char *pStr; Does not allocate string memory It is useful in referring to C-strings defined as string literals pStr = "Hi there"; cout << pStr << " " << pStr; // prints: Hi there Hi there 12-12

  13. Pointer to char Major advantage of using a pointer variable to represent a C-string is the ability to make the pointer point to different C-strings char name[]= John Doe"; char *p; p = name; cout << p << endl; p = Jane Doe cout << p << endl; // prints: // John Doe // Jane Doe 12-13

  14. Pointer to char Another way to use a pointer to a character as a C-string is to define the pointer and then set it to point to dynamically allocated storage returned by the new operator. char *pname = nullptr; pname = new char[50]; cout << Enter your name: ; cin.getline(pname, 50); cout << Hello << pname; delete[] pname; 12-14

  15. What is a NULL pointer? A local pointer variable that has not been initialized does not hold a valid address, and an attempt to use such a pointer will result in execution-time errors. int *ptr = 0; // old C++ style int *ptr = NULL; // NULL is a constant // defined in header files // such as iostream, // fstream, and cstdlib int *ptr = nullptr; // new C++11 12-15

  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 string literal 12-16

  17. Library Functions for Working with C-Strings strlen int strlen(char *str) Returns length of a C-string: cout << strlen("hello"); // prints: 5 Note: This is the number of characters in the string, not including the terminating null, NOT the size of the array that contains it 12-17

  18. Library Functions for Working with C-Strings strcat strcat(char *dest, char *source) Takes two C-strings as input. It adds the contents of the second string to the end of the first string: char str1[15] = "Good "; char str2[30] = "Morning!"; strcat(str1, str2); cout << str1; // prints: Good Morning! No automatic bounds checking: programmer must ensure that 1st string has enough room for result 12-18

  19. Library Functions for Working with C-Strings 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 Bounds checking is up to the programmer. 12-19

  20. Library Functions for Working with C-Strings 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 12-20

  21. strcmp It can be used to test for equality if(strcmp(str1, str2) == 0) cout << "They are equal"; else cout << "They are not equal"; Also used to determine ordering of C-strings in sorting applications Note: Comparisons are case-sensitive: "Hi" is not "hi" C-strings cannot be compared using relational operators (compares addresses of C-strings, not contents) 12-21

  22. 12.3 Conversions Between Numbers and Strings "4326" is a string; 4326 without quotes is an int There are classes that can be used to convert between string and numeric forms of numbers Need to include sstream header file 12-22

  23. Conversion Classes ostringstream: subclass of ostream (the class that cout belongs to) uses the stream insertion operator << to convert numeric values to a string; to add data onto the string instead of writing to the screen (like cout objects and file objects), ostringstream writes its data to a string object Use str() to retrieve converted string Each time you use << on an ostringstream object, it performs any numeric-to-string conversions necessary and appends the result onto the end of its string. 12-23

  24. Conversion Classes istringstream: derives from istream contains a string object that functions as an input stream that can be read from can be set by the istringstream constructor when the object is created, or by calling str(string s) function after the object has been created the stream extraction operator >> reads from the enclosed string and converts from string to numeric where necessary. 12-24

  25. Conversion Classes Member functions of both ostringstream and istringstream: ostringstream(string s) constructor example: ostringstream ostr( 50 64 28 ); istringstream(string s). constructor example: istringstream istr( 50 64 28 ); 12-25

  26. Conversion Classes Member functions of both ostringstream and istringstream (continued): string str() returns the string contained in the ostringstream or istringstream object example: string os = ostr.str(); string is = istr.str(); void str(string &s) sets the string that serves as the input or output stream for the object example: ostr.str( 50 64 28 ); istr.str( 50 64 28 ); 12-26

  27. string str = "John 20 50"; // String to read from const char *cstr = "Amy 30 42"; // Cstring to read from istringstream istr1(str); // istr1 will read from str istringstream istr2; // istr2 will read from cstr ostringstream ostr; // The ostringstream object // to write to string name; int score1, score2, average_score; // Read name and scores and compute average // then write to ostr istr1 >> name >> score1 >> score2; average_score = (score1 + score2)/2; ostr << name << " has average score " << average_score << "\n"; // Set istr2 to read from the C string and repeat the above istr2.str(cstr); istr2 >> name >> score1 >> score2; average_score = (score1 + score2)/2; ostr << name << " has average score " << average_score << "\n"; 12-27

  28. Numeric Conversion Functions Introduced in C++ 11 Allow conversion between numeric values and strings to_string() convert a numeric value to a string stoi() convert a string to an int stol() convert a string to a long stof() convert a string to a float stod() convert a string to a double 12-28

  29. Example - stoi stoi converts string toint int stoi(const string& str, size_t* pos = 0, int base = 10) str: string containing the number, possibly other chars pos: the position in str where conversion stops (optional parm) base: the base to use for integral conversion (optional parm) Example: int number; size_t where; string data = "23 skidoo"; number = stoi(data, &where); // number will // have 23 // where has 2 12-29

  30. Example - stoi string str; size_t pos; str = "-342.57is a number"; cout << "\nThe string is " << str << endl; int i = stoi(str, &pos); cout << "The converted integer is " << i << endl; cout << "The stopping character is " << str[pos] << " at position " << pos << endl; // prints: // The string is -342.57is a number // The converted integer is -342 // The stopping character is . at position 4 12-30

  31. Example - stoi string str; size_t pos; str = "01110binary number"; cout << "\nThe string is " << str << endl; i = stoi(str, &pos, 2); cout << "The converted binary integer is " << i << endl; cout << "The stopping character is " << str[pos] << " at position " << pos << endl; // prints: // The string is 01110binary number // The converted binary integer is 14 // The stopping character is b at position 5 12-31

  32. Example - stod string str; size_t pos; str = "-342.57is a number"; cout << "The string is " << str << endl; double d = stod(str, &pos); cout << "The converted double is " << d << endl; cout << "The stopping character is " << str[pos] << " at position " << pos << endl; // prints: // The string is -342.57is a number // The converted double is -342.57 // The stopping character is i at position 7 12-32

  33. 12.5 More About the C++ string Class The string class offers several advantages over C-style strings: large body of member functions overloaded operators to simplify expressions Need to include the string header file 12-33

  34. string class constructors Default constructor string() Copy constructor string(string&) initializes new string objects with values of other existing string objects Convert constructor string(char *) initializes new string objects with values of C- strings 12-34

  35. Overloaded string Operators OPERATOR MEANING reads a whitespace-delimited string into a string object inserts a string object into a stream >> << assigns string on right to string object on left appends copy of string on the right to the end of contents of string object on left = += 12-35

  36. Overloaded string Operators (continued) OPERATOR MEANING Returns concatenation of the two strings references character in string using array-subscript notation relational operators for string comparison. Return true or false + [] >, >=, <, <=, ==, != 12-36

  37. Overloaded string Operators string word1, phrase; 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 < 16; i++) cout << phrase[i]; // displays // "Hot Dog on a bun" 12-37

  38. 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,size substrings: find,substr comparison: compare 12-38

  39. Conversion to C-strings data() and c_str() both return the C- string equivalent of a string object Useful when 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()); // strcat(greeting, str.c_str()); 12-39

  40. Modification of string objects str.append(string s) appends contents of s to end of str s can be a string object or a C-string string str("Have a "); string str2("nice "); str.append(str2); // string object str.append("day"); // convert // constructor so // can use a c-string // prints: // Have a nice day append is overloaded for flexibility (3 other versions listed on page 841 in book) 12-40

  41. Modification of string objects str.insert(int pos, string s) inserts s at position pos in str string str("Have day"); string str2("a "); str.insert(5, str2); // string object str.insert(7, "nice "); // convert constructor // so can use a c- // string // prints: // Have a nice day insert is overloaded for flexibility 12-41

More Related Content