CStrings and the string Class 12 1 CStrings

  • Slides: 41
Download presentation
C-Strings and the string Class

C-Strings and the string Class

12. 1 C-Strings • C-string: sequence of characters stored in adjacent memory locations and

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: H 12 -2 i t h e r e !

What is NULL character? • The null character is used to indicate the end

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

Representation of C-strings As a string literal "Hi There!" As a pointer to char

Representation of C-strings As a string literal "Hi There!" As a pointer to char *p; As an array of characters char str[20]; All three representations are pointers to char 12 -4

String Literals • A string literal (string constant) is stored as a null-terminated array

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 address of this array 12 -5 h i

const char *p = nullptr, *q = nullptr; p = “Hello ”; q =

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

Array of char • An array of char can be defined and initialized to

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

const int LENGTH = 80; char line[LENGTH]; cout << “Enter a sentence of no

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] != ‘’; i++) cout << line[i]; 12 -8

C-Strings • A string literal allocates an array and then uses the address of

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

C-Strings • A C-string represented as an array of characters also allocates an array

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

C-Strings • The third method of representing a C-string uses a pointer to a

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

Pointer to char • Defined as char *p. Str; • Does not allocate string

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

Pointer to char • Major advantage of using a pointer variable to represent a

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

Pointer to char • Another way to use a pointer to a character as

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

What is a NULL pointer? • A local pointer variable that has not been

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; int *ptr = NULL; // // // int *ptr = nullptr; // 12 -15 old C++ style NULL is a constant defined in header files such as iostream, fstream, and cstdlib new C++11

12. 2 Library Functions for Working with C-Strings • Require cstring header file •

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

Library Functions for Working with C-Strings strlen int strlen(char *str) Returns length of a

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

Library Functions for Working with C-Strings strcat(char *dest, char *source) • Takes two C-strings

Library Functions for Working with C-Strings 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 str 1[15] = "Good "; char str 2[30] = "Morning!"; strcat(str 1, str 2); cout << str 1; // prints: Good Morning! • No automatic bounds checking: programmer must ensure that 1 st string has enough room for result 12 -18

Library Functions for Working with C-Strings strcpy(char *dest, char *source) • Copies a string

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

Library Functions for Working with C-Strings strcmp int strcmp(char *str 1, char*str 2) •

Library Functions for Working with C-Strings strcmp int strcmp(char *str 1, char*str 2) • Compares strings stored at two addresses to determine their relative alphabetic order: • Returns a value: less than 0 if str 1 precedes str 2 equal to 0 if str 1 equals str 2 greater than 0 if str 1 succeeds str 2 12 -20

strcmp • It can be used to test for equality if(strcmp(str 1, str 2)

strcmp • It can be used to test for equality if(strcmp(str 1, str 2) == 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

12. 3 Conversions Between Numbers and Strings • "4326" is a string; 4326 without

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

Conversion Classes • ostringstream: – subclass of ostream (the class that cout belongs to)

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

Conversion Classes • istringstream: – derives from istream – contains a string object that

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

Conversion Classes Member functions of both ostringstream and istringstream: ostringstream(string s) constructor example: ostringstream

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

Conversion Classes Member functions of both ostringstream and istringstream (continued): string str() returns the

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

string str = "John 20 50"; const char *cstr = "Amy 30 42"; istringstream

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

Numeric Conversion Functions • Introduced in C++ 11 • Allow conversion between numeric values

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

Example - stoi • stoi converts string to int stoi(const string& str, size_t* pos

Example - stoi • stoi converts string to 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

Example - stoi string str; size_t pos; str = "-342. 57 is a number";

Example - stoi string str; size_t pos; str = "-342. 57 is a number"; cout << "n. The 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; // // 12 -30 prints: The string is -342. 57 is a number The converted integer is -342 The stopping character is. at position 4

Example - stoi string str; size_t pos; str = "01110 binary number"; cout <<

Example - stoi string str; size_t pos; str = "01110 binary number"; cout << "n. The 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; // // 12 -31 prints: The string is 01110 binary number The converted binary integer is 14 The stopping character is b at position 5

Example - stod string str; size_t pos; str = "-342. 57 is a number";

Example - stod string str; size_t pos; str = "-342. 57 is 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; // // 12 -32 prints: The string is -342. 57 is a number The converted double is -342. 57 The stopping character is i at position 7

12. 5 More About the C++ string Class • The string class offers several

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

string class constructors • Default constructor string() • Copy constructor string(string&) initializes new string

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 Cstrings 12 -34

Overloaded string Operators OPERATOR >> << = += 12 -35 MEANING reads a whitespace-delimited

Overloaded string Operators OPERATOR >> << = += 12 -35 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

Overloaded string Operators (continued) OPERATOR + [] >, >=, <, <=, ==, != 12

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

Overloaded string Operators string word 1, phrase; string word 2 = " Dog"; cin

Overloaded string Operators string word 1, phrase; string word 2 = " Dog"; cin >> word 1; // user enters "Hot" // word 1 has "Hot" phrase = word 1 + word 2; // 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

string Member Functions Categories: – conversion to C-strings: c_str, data – modification: append, assign,

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

Conversion to C-strings • data() and c_str() both return the Cstring equivalent of a

Conversion to C-strings • data() and c_str() both return the Cstring 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

Modification of string objects • str. append(string s) – appends contents of s to

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 str("Have a "); string str 2("nice "); str. append(str 2); // 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

Modification of string objects • str. insert(int pos, string s) – inserts s at

Modification of string objects • str. insert(int pos, string s) – inserts s at position pos in string str("Have day"); string str 2("a "); str. insert(5, str 2); // 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