Chapter 15 Class string and String Stream Processing
- Slides: 52
Chapter 15 - Class string and String Stream Processing Outline 15. 1 15. 2 15. 3 15. 4 15. 5 15. 6 15. 7 15. 8 15. 9 15. 10 15. 11 15. 12 Introduction string Assignment and Concatenation Comparing strings Substrings Swapping strings string Characteristics Finding Strings and Characters in a string Replacing Characters in a string Inserting Characters into a string Conversion to C-Style char * Strings Iterators String Stream Processing 2003 Prentice Hall, Inc. All rights reserved. 1
2 15. 1 Introduction • Template class basic_string – String manipulation (copying, searching, etc. ) • typedef basic_string< char > string; • Also typedef for wchar_t – Include <string> • string initialization – string s 1( "Hello" ); – string s 2( 8, 'x' ); • 8 'x' characters – string month = "March" • Implicitly calls constructor 2003 Prentice Hall, Inc. All rights reserved.
3 15. 1 Introduction • No conversion from int or char – The following definitions are errors • string error 1 = 'c'; • string error 2( 'u' ); • string error 3 = 22; • string error 4( 8 ); – However, can assign to one char if declared • s = 'n'; 2003 Prentice Hall, Inc. All rights reserved.
4 15. 1 Introduction • string features – Not necessarily null terminated – length member function: s 1. length() – Use [] to access individual characters: s 1[0] • 0 to length-1 – string not a pointer – Many member functions take start position and length • If length argument too large, max chosen – Stream extraction • cin >> string. Object; • getline( cin, s) – Delimited by newline 2003 Prentice Hall, Inc. All rights reserved.
5 15. 2 string Assignment and Concatenation • Assignment – s 2 = s 1; • Makes a separate copy – s 2. assign(s 1); • Same as s 2 = s 1; – my. String. assign(s, start, N); • Copies N characters from s, beginning at index start – Individual characters • s 2[0] = s 3[2]; 2003 Prentice Hall, Inc. All rights reserved.
6 15. 2 string Assignment and Concatenation • Range checking – s 3. at( index ); • Returns character at index • Can throw out_of_range exception – [] has no range checking • Concatenation – s 3. append( "pet" ); – s 3 += "pet"; • Both add "pet" to end of s 3 – s 3. append( s 1, start, N ); • Appends N characters from s 1, beginning at index start 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 15. 1: fig 15_01. cpp // Demonstrating string assignment and concatenation. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <string> 9 10 using std: : string; 11 12 13 14 15 16 int main() { string 1( "cat" ); string 2; string 3; 17 18 19 20 21 Outline String initialization and assignment. Output string 1: cat string 2: cat string 3: cat string 2 = string 1; // assign string 1 to string 2 string 3. assign( string 1 ); // assign string 1 to string 3 cout << "string 1: " << string 1 << "nstring 2: " << string 2 << "nstring 3: " << string 3 << "nn"; fig 15_01. cpp (1 of 3) 22 2003 Prentice Hall, Inc. All rights reserved. 7
23 24 // modify string 2 and string 3 string 2[ 0 ] = string 3[ 2 ] = 'r'; 25 26 27 28 cout << "After modification of string 2 and string 3: n" << "string 1: " << string 1 << "nstring 2: " << string 2 << "nstring 3: "; 29 30 31 32 Outline 33 34 35 36 // demonstrating member function at After modification of string 2 and string 3: for ( int i = 0; i < string 3. length(); i++ ) string 1: cat cout << string 3. at( i ); string 2: rat string 3: car // declare string 4 and string 5 fig 15_01. cpp string 4( string 1 + "apult" ); Note use of member function string 5; (2 of 3) 37 38 39 40 // overloaded += string 3 += "pet"; // create "carpet" string 1. append( "acomb" ); // create "catacomb" 41 42 43 44 45 46 47 48 49 50 at instead of []. After concatenation: string 1: catacomb string 2: rat // append subscript locations 4 through end of string 1 to string 3: carpet // create string "comb" (string 5 was initially empty) string 4: catapult string 5. append( string 1, 4, string 1. length() ); string 5: comb cout << "nn. After concatenation: nstring 1: " << string 1 << "nstring 2: " << string 2 << "nstring 3: " << string 3 << "nstring 4: " << string 4 << "nstring 5: " << string 5 << endl; 2003 Prentice Hall, Inc. All rights reserved. 8
51 return 0; 52 string 1: cat 53 } // end main Outline string 2: cat string 3: cat After modification of string 2 and string 3: string 1: cat string 2: rat string 3: car After concatenation: string 1: catacomb string 2: rat string 3: carpet string 4: catapult string 5: comb fig 15_01. cpp (3 of 3) fig 15_01. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 9
10 15. 3 Comparing strings • Overloaded operators – ==, !=, <, >, <= and >= – Return bool • s 1. compare(s 2) – Returns positive if s 1 lexicographically greater • Compares letter by letter • 'B' lexicographically greater than 'A' – Returns negative if less, zero if equal – s 1. compare(start, length, s 2, start, length) • Compare portions of s 1 and s 2 – s 1. compare(start, length, s 2) • Compare portion of s 1 with all of s 2 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 15. 2: fig 15_02. cpp // Demonstrating string comparison capabilities. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <string> 9 10 using std: : string; 11 12 13 14 15 16 17 18 int main() { string 1( "Testing the comparison functions. " ); string 2( "Hello" ); string 3( "stinger" ); string 4( string 2 ); Outline fig 15_02. cpp (1 of 4) 2003 Prentice Hall, Inc. All rights reserved. 11
19 20 21 cout << "string 1: " << string 1 << "nstring 2: " << string 2 << "nstring 3: " << string 3 << "nstring 4: " << string 4 << "nn"; 22 23 24 25 26 27 28 29 30 31 // comparing string 1 and string 4 if ( string 1 == string 4 ) cout << "string 1 == string 4n"; else { // string 1 != string 4 if ( string 1 > string 4 ) cout << "string 1 > string 4n"; else // string 1 < string 4 cout << "string 1 < string 4n"; } 32 33 34 // comparing string 1 and string 2 int result = string 1. compare( string 2 ); 35 36 37 38 39 40 41 42 if ( result == 0 ) cout << "string 1. compare( string 2 ) == 0n" ; else // result != 0 if ( result > 0 ) cout << "string 1. compare( string 2 ) > 0n" ; else // result < 0 cout << "string 1. compare( string 2 ) < 0n" ; Outline Note use of overloaded == operator. string 1: Testing the comparison functions. string 2: Hello string 3: stinger string 4: Hello string 1 > string 4 fig 15_02. cpp (2 of 4) 43 2003 Prentice Hall, Inc. All rights reserved. 12
44 45 // comparing string 1 (elements 2 -5) and string 3 (elements 0 -5) result = string 1. compare( 2, 5, string 3, 0, 5 ); 46 47 48 49 50 51 52 53 if ( result == 0 ) cout << "string 1. compare( 2, 5, string 3, 0, 5 ) == 0n" ; else // result != 0 if ( result > 0 ) cout << "string 1. compare( 2, 5, string 3, 0, 5 ) > 0n" ; else // result < 0 cout << "string 1. compare( 2, 5, string 3, 0, 5 ) < 0n" ; 54 55 56 // comparing string 2 and string 4 result = string 4. compare( 0, string 2. length(), string 2 ); 57 58 59 60 61 62 63 64 65 66 67 68 if ( result == 0 ) cout << "string 4. compare( 0, string 2. length(), " << "string 2 ) == 0" << endl; else // result != 0 if ( result > 0 ) cout << "string 4. compare( 0, string 2. length(), " << "string 2 ) > 0" << endl; else // result < 0 cout << "string 4. compare( 0, string 2. length(), " << "string 2 ) < 0" << endl; Outline Note use of compare. fig 15_02. cpp (3 of 4) 2003 Prentice Hall, Inc. All rights reserved. 13
69 70 // comparing string 2 and string 4 result = string 2. compare( 0, 3, string 4 ); 71 72 73 74 75 76 77 78 if ( result == 0 ) cout << "string 2. compare( 0, 3, string 4 ) == 0" << endl; else // result != 0 if ( result > 0 ) cout << "string 2. compare( 0, 3, string 4 ) > 0" << endl; else // result < 0 cout << "string 2. compare( 0, 3, string 4 ) < 0" << endl; 79 80 return 0; 81 82 } // end main string 1: Testing the comparison functions. string 2: Hello string 3: stinger string 4: Hello string 1 > string 4 string 1. compare( string 2 ) > 0 string 1. compare( 2, 5, string 3, 0, 5 ) == 0 string 4. compare( 0, string 2. length(), string 2 ) == 0 Outline fig 15_02. cpp (4 of 4) fig 15_02. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 14
15 15. 4 Substrings • Function substr gets substring – s 1. substr( start, N ); – Gets N characters, beginning with index start – Returns substring 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 15. 3: fig 15_03. cpp // Demonstrating string member function substr. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <string> 9 10 using std: : string; 11 12 13 14 int main() { string 1( "The airplane landed on time. " ); 15 16 17 18 // retrieve substring "plane" which // begins at subscript 7 and consists of 5 elements cout << string 1. substr( 7, 5 ) << endl; 19 20 return 0; 21 22 } // end main Outline fig 15_03. cpp (1 of 1) fig 15_03. cpp Note usage of substr. output (1 of 1) plane 2003 Prentice Hall, Inc. All rights reserved. 16
17 15. 5 Swapping strings • s 1. swap(s 2); – Switch contents of two strings 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 15. 4: fig 15_04. cpp // Using the swap function to swap two strings. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <string> 9 10 using std: : string; 11 12 13 14 15 int main() { string first( "one" ); string second( "two" ); 16 17 18 19 // output strings Call swap. cout << "Before swap: n first: " << first << "nsecond: " << second; 20 21 first. swap( second ); // swap strings 22 23 24 25 26 cout << "nn. After swap: n first: " << first << "nsecond: " << second << endl; return 0; 27 28 } // end main Outline fig 15_04. cpp (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 18
Before swap: first: one second: two Outline After swap: first: two second: one fig 15_04. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 19
20 15. 6 string Characteristics • Member functions – s 1. size() and s 1. length() • Number of characters in string – s 1. capacity() • Number of elements that can be stored without reallocation – s 1. max_size() • Maximum possible string size – s 1. empty() • Returns true if empty – s 1. resize(newlength) • Resizes string to newlength 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 15. 5: fig 15_05. cpp // Demonstrating member functions related to size and capacity. #include <iostream> 4 5 6 7 8 using std: : cout; using std: : endl; using std: : cin; using std: : boolalpha; 9 10 #include <string> 11 12 using std: : string; 13 14 void print. Statistics( const string & ); 15 16 17 18 19 20 21 int main() { string 1; cout << "Statistics before input: n" << boolalpha; print. Statistics( string 1 ); 22 23 24 25 26 // read in "tomato" cout << "nn. Enter a string: "; cin >> string 1; // delimited by whitespace cout << "The string entered was: " << string 1; Outline fig 15_05. cpp (1 of 3) 2003 Prentice Hall, Inc. All rights reserved. 21
27 28 29 cout << "n. Statistics after input: n"; print. Statistics( string 1 ); 30 31 32 33 34 // read in "soup" cin >> string 1; // delimited by whitespace cout << "nn. The remaining string is: " << string 1 << endl; print. Statistics( string 1 ); 35 36 37 38 39 // append 46 characters to string 1 += "1234567890 abcdefghijklmnopqrstuvwxyz 1234567890" ; cout << "nnstring 1 is now: " << string 1 << endl; Resize string. print. Statistics( string 1 ); 40 41 42 43 44 // add 10 elements to string 1. resize( string 1. length() + 10 ); cout << "nn. Stats after resizing by (length + 10): n" ; print. Statistics( string 1 ); 45 46 47 cout << endl; return 0; 48 49 } // end main Outline fig 15_05. cpp (2 of 3) 50 2003 Prentice Hall, Inc. All rights reserved. 22
51 52 53 54 55 56 57 58 // display string statistics void print. Statistics( const string &string. Ref ) { cout << "capacity: " << string. Ref. capacity() << "nmax size: " << string. Ref. max_size() << "nsize: " << string. Ref. size() << "nlength: " << string. Ref. length() << "nempty: " << string. Ref. empty(); 59 60 } // end print. Statistics before input: capacity: 0 max size: 4294967293 size: 0 length: 0 empty: true Enter a string: tomato soup The string entered was: tomato Statistics after input: capacity: 31 Display various string Outline characteristics. fig 15_05. cpp (3 of 3) fig 15_05. cpp output (1 of 2) 2003 Prentice Hall, Inc. All rights reserved. 23
The remaining string is: soup capacity: 31 max size: 4294967293 size: 4 length: 4 empty: false string 1 is now: soup 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 capacity: 63 max size: 4294967293 size: 50 length: 50 empty: false Stats after resizing by (length + 10): capacity: 63 max size: 4294967293 size: 60 length: 60 empty: false Outline fig 15_05. cpp output (2 of 2) 2003 Prentice Hall, Inc. All rights reserved. 24
15. 7 Finding Strings and Characters in a string • Find functions – If found, index returned – If not found, string: : npos returned • Public static constant in class string – s 1. find( s 2 ) – s 1. rfind( s 2 ) • Searches right-to-left – s 1. find_first_of( s 2 ) • Returns first occurrence of any character in s 2 • s 1. find_frist_of( "abcd" ) – Returns index of first 'a', 'b', 'c' or 'd' 2003 Prentice Hall, Inc. All rights reserved. 25
15. 7 Finding Strings and Characters in a string • Find functions – s 1. find_last_of( s 2 ) • Finds last occurrence of any character in s 2 – s 1. find_first_not_of( s 2 ) • Finds first character NOT in s 2 – s 1. find_last_not_of( s 2 ) • Finds last character NOT in s 2 2003 Prentice Hall, Inc. All rights reserved. 26
1 2 3 // Fig. 15. 6: fig 15_06. cpp // Demonstrating the string find member functions #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <string> 9 10 using std: : string; 11 12 13 14 15 16 17 18 19 20 21 22 int main() fig 15_06. cpp { string 1( "noon is 12 p. m. " ); (1 of 3) int location; Note call to function find. // find "is" at location 5 cout << "Original string: n" << string 1 << "nn(find) "is" was found at: " << string 1. find( "is" ) << "n(rfind) "is" was found at: " Find first occurrence of m, i, << string 1. rfind( "is" ); 23 24 25 // find 'o' at location 1 location = string 1. find_first_of( "misop" ); Outline s, o or p. 2003 Prentice Hall, Inc. All rights reserved. 27
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 Outline cout << "nn(find_first_of) found '" << string 1[ location ] << "' from the group "misop" at: " Calls to other find functions << location; similar. // find 'm' at location 13 location = string 1. find_last_of( "misop" ); cout << "nn(find_last_of) found '" << string 1[ location ] << "' from the group "misop" at: " << location; // find '1' at location 8 fig 15_06. cpp location = string 1. find_first_not_of( "noi spm" ); cout << "nn(find_first_not_of) '" << string 1[ location ] (2 of 3) << "' is not contained in " noi spm" and was found at: " << location; // find '. ' at location 12 location = string 1. find_first_not_of( "12 noi spm" ); cout << "nn(find_first_not_of) '" << string 1[ location ] << "' is not contained in "12 noi spm" and was " << "found at: " << location << endl; 2003 Prentice Hall, Inc. All rights reserved. 28
48 49 50 51 52 // search for characters not in string 1 location = string 1. find_first_not_of( "noon is 12 p. m. " ); cout << "nfind_first_not_of("noon is 12 p. m. ")" << " returned: " << location << endl; 53 54 return 0; 55 56 } // end main Original string: noon is 12 p. m. (find) "is" was found at: 5 (rfind) "is" was found at: 5 (find_first_of) found 'o' from the group "misop" at: 1 (find_last_of) found 'm' from the group "misop" at: 13 (find_first_not_of) '1' is not contained in "noi spm" and was found at: 8 Outline fig 15_06. cpp (3 of 3) fig 15_06. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 29
30 15. 8 Replacing Characters in a string • s 1. erase( start ) – Erase from index start to end of string, including start • Replace – s 1. replace( begin, N, s 2) • begin: index in s 1 to start replacing • N: number of characters to replace • s 2: replacement string – s 1. replace( begin, N, s 2, index, num ) • index: element in s 2 where replacement begins • num: number of elements to use when replacing – Replacement can overwrite characters – string: : npos represents max string length 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 15. 7: fig 15_07. cpp // Demonstrating string member functions erase and replace. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <string> 9 10 using std: : string; 11 12 13 14 15 16 17 18 19 20 21 int main() { // compiler concatenates all parts into one string 1( "The values in any left subtree" "nare less than the value in the" "nparent node and the values in" "nany right subtree are greater" "nthan the value in the parent node" ); cout << "Original string: n" << string 1 << endl; 22 23 24 25 // remove all characters from (and including) location 62 // through the end of string 1 string 1. erase( 62 ); Outline fig 15_07. cpp (1 of 2) 26 2003 Prentice Hall, Inc. All rights reserved. 31
27 28 29 30 31 32 // output new string: : npos represents cout << "Original string after erase: n" << string 1 max string length. << "nn. After first replacement: n"; // replace all spaces with period Find each space and replace int position = string 1. find( " " ); 33 34 35 36 37 38 39 40 41 42 43 while ( position != string: : npos ) { string 1. replace( position, 1, ". " ); position = string 1. find( " ", position + 1 ); } // end while fig 15_07. cpp cout << string 1 << "nn. After second replacement: n"; Start each search at the next (2 of 2) position. // replace all periods with two semicolons // NOTE: this will overwrite characters Replace all '. ' with two position = string 1. find( ". " ); 44 45 46 47 48 while ( position != string: : npos ) { string 1. replace( position, 2, "xxxxx; ; yyy", 5, 2 ); position = string 1. find( ". ", position + 1 ); } // end while 49 50 51 cout << string 1 << endl; return 0; 52 53 } // end main Outline with a '. ' semicolons (the two characters at index 5). 2003 Prentice Hall, Inc. All rights reserved. 32
Original string: The values in any left subtree are less than the value in the parent node and the values in any right subtree are greater than the value in the parent node Outline Original string after erase: The values in any left subtree are less than the value in the After first replacement: The. values. in. any. left. subtree are. less. than. the. value. in. the fig 15_07. cpp output (1 of 1) After second replacement: The; ; alues; ; ny; ; eft; ; ubtree are; ; ess; ; han; ; he; ; alue; ; n; ; he 2003 Prentice Hall, Inc. All rights reserved. 33
34 15. 9 Inserting Characters into a string • s 1. insert( index, s 2 ) – Inserts s 2 before position index • s 1. insert( index, s 2, index 2, N ); – Inserts substring of s 2 before position index – Substring is N characters, starting at index 2 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 15. 8: fig 15_08. cpp // Demonstrating class string insert member functions. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <string> 9 10 using std: : string; 11 12 13 14 15 16 17 int main() { string 1( "beginning end" ); string 2( "middle " ); string 3( "12345678" ); string 4( "xx" ); 18 19 20 21 cout << "Initial strings: nstring 1: " << string 1 << "nstring 2: " << string 2 << "nstring 3: " << string 3 Insert all of string 2 before << "nstring 4: " << string 4 << "nn"; 22 23 24 // insert "middle" at location 10 in string 1. insert( 10, string 2 ); Outline fig 15_08. cpp (1 of 2) element 10. 25 2003 Prentice Hall, Inc. All rights reserved. 35
26 27 // insert "xx" at location 3 in string 3. insert( 3, string 4, 0, string: : npos ); 28 29 30 31 cout << "Strings after insert: nstring 1: " << string 1 << "nstring 2: " << string 2 << "nstring 3: " << string 3 << "nstring 4: " << string 4 << endl; 32 33 return 0; 34 35 } // end main Outline Insert all of string 4 before index 3. Initial strings: string 1: beginning end string 2: middle string 3: 12345678 string 4: xx Strings after insert: string 1: beginning middle end string 2: middle string 3: 123 xx 45678 string 4: xx fig 15_08. cpp (2 of 2) fig 15_08. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 36
37 15. 10 Conversion to C-Style char * Strings • Conversion functions – strings not necessarily null-terminated – s 1. copy( ptr, N, index ) • Copies N characters into the array ptr • Starts at location index • Need to null terminate – s 1. c_str() • Returns const char * • Null terminated – s 1. data() • Returns const char * • NOT null-terminated 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 15. 9: fig 15_09. cpp // Converting to C-style strings. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <string> 9 10 using std: : string; 11 12 13 14 15 16 17 18 19 20 21 int main() { Note calls to copy and string 1( "STRINGS" ); c_str. const char *ptr 1 = 0; int length = string 1. length(); char *ptr 2 = new char[ length + 1 ]; // including null // copy characters from string 1 into allocated memory string 1. copy( ptr 2, length, 0 ); ptr 2[ length ] = '