2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Chapter 19 - Class string and Stream Processing
Outline19.1 Introduction19.2 string Assignment and Concatenation19.3 Comparing strings19.4 Substrings19.5 Swapping strings19.6 string Characteristics19.7 Finding Characters in a string19.8 Replacing Characters in a string19.9 Inserting Characters into a string19.10 Conversion to C-Style char * Strings19.11 Iterators19.12 String Stream Processing
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.1Introduction
• template class basic_string– typedef basic_string< char > string;
• creates alias string for basic_string< char > which we use
– include <string>
• Initialization– string s1( "Hi");– string s2( 8, 'x');– string name = "Jim";
• not truly assignment, calls copy constructor
WRONG:string s1 = 'c';string s2( 'u' );string s3 = 34;string s4( 8 );
• no automatic conversion between int or char to string
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.1Introduction (II)
• strings do not always end in '\0'• use the [] operator to access elements
– first subscript 0– string not a pointer. &string1[0] != string1
• String length - s1.size() or s1.length() • Inputting strings
string myString;
cin >> myString;• delimited by whitespace characters
string myString;
getline(cin, myString);• overloaded getline function
• delimited by newline ('\n')
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.2string Assignment and Concatenation
• String assignment– = operator: s2 = s1;– assign(): s2.assign(s1);
• copies s1 into s2– s2.assign(s1, startSubscript, numberOfChars);
• copies numberOfChars characters in s1 to s2, starting from startSubscript
– s2[0] = 'm'; • sets first character of s2 to 'm'
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.2string Assignment and Concatenation (II)
• More string operations– s2.at(2);
• range checked access
– s2 += "hi" • concatenates s2 and "hi"
– s2.append("_again"); • concatenates "_again" and s2
– s2.append(s1, startSubscript, numberOfChars);• concatenates numberOfChars characters in s1 with s2,
starting from startSubscript
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
1. Initialize strings
2. Modify strings
3. Print strings
1 // Fig. 19.1: fig19_01.cpp2 // Demonstrating string assignment and concatenation3 #include <iostream>45 using std::cout;6 using std::endl;78 #include <string>910 using std::string;1112 int main()13 {14 string s1( "cat" ), s2, s3;1516 s2 = s1; // assign s1 to s2 with =17 s3.assign( s1 ); // assign s1 to s3 with assign()18 cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: "19 << s3 << "\n\n";2021 // modify s2 and s3 22 s2[ 0 ] = s3[ 2 ] = 'r';2324 cout << "After modification of s2 and s3:\n"25 << "s1: " << s1 << "\ns2: " << s2 << "\ns3: "; 2627 // demonstrating member function at()28 int len = s3.length();29 for ( int x = 0; x < len; ++x ) 30 cout << s3.at( x );3132 // concatenation
s1: cat
s2: cat
s3: cat
After modification of s2 and s3:
s1: cat
s2: rat
s3: car
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
3. Print strings
Program Output
33 string s4( s1 + "apult" ), s5; // declare s4 and s5
34
35 // overloaded +=
36 s3 += "pet"; // create "carpet"
37 s1.append( "acomb" ); // create "catacomb"
38
39 // append subscript locations 4 thru the end of s1 to
40 // create the string "comb" (s5 was initially empty)
41 s5.append( s1, 4, s1.size() );
42
43 cout << "\n\nAfter concatenation:\n" << "s1: " << s1
44 << "\ns2: " << s2 << "\ns3: " << s3 << "\ns4: " << s4
45 << "\ns5: " << s5 << endl;
46
47 return 0;
48 }
s1: cats2: cats3: cat After modification of s2 and s3:s1: cats2: rats3: car After concatenation:s1: catacombs2: rats3: carpets4: catapults5: comb
After concatenation:
s1: catacomb
s2: rat
s3: carpet
s4: catapult
s5: comb
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.3Comparing strings
• overloaded ==, !=, <, >, <= and >= operators – for string comparisons – return bool values
• result = s1.compare(s2);– lexicographical comparison– if s1 > s2, result > 0– if s1 < s2, result < 0– if s1 == s2, result = 0
s1.compare(sub1, sub2, s2, sub3, sub4)compares s1 from subscript sub1 to sub2 with s2 from subscript sub3 to sub4.
s1.compare(sub1, number, s2)compares number characters in s1 starting from subscript sub1 with s2.
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
1. Initialize strings
2. Compare strings
1 // Fig. 19.2: fig19_02.cpp2 // Demonstrating string comparison capabilities3 #include <iostream>45 using std::cout;6 using std::endl;78 #include <string>910 using std::string;1112 int main()13 {14 string s1( "Testing the comparison functions." ),15 s2("Hello" ), s3( "stinger" ), z1( s2 );16 17 cout << "s1: " << s1 << "\ns2: " << s218 << "\ns3: " << s3 << "\nz1: " << z1 << "\n\n";1920 // comparing s1 and z121 if ( s1 == z1 )22 cout << "s1 == z1\n";23 else { // s1 != z1 24 if ( s1 > z1 )25 cout << "s1 > z1\n";26 else // s1 < z127 cout << "s1 < z1\n";28 }2930 // comparing s1 and s231 int f = s1.compare( s2 );3233 if ( f == 0)
s1: Testing the comparison functions.
s2: Hello
s3: stinger
z1: Hello
s1 > z1
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
2. Compare strings
34 cout << "s1.compare( s2 ) == 0\n";
35 else if ( f > 0 )
36 cout << "s1.compare( s2 ) > 0\n";
37 else // f < 0
38 cout << "s1.compare( s2 ) < 0\n";
39
40 // comparing s1 (elements 2 - 5) and s3 (elements 0 - 5)
41 f = s1.compare( 2, 5, s3, 0, 5 );
42
43 if ( f == 0 )
44 cout << "s1.compare( 2, 5, s3, 0, 5 ) == 0\n";
45 else if ( f > 0 )
46 cout << "s1.compare( 2, 5, s3, 0, 5 ) > 0\n";
47 else // f < 0
48 cout << "s1.compare( 2, 5, s3, 0, 5 ) < 0\n";
49
50 // comparing s2 and z1
51 f = z1.compare( 0, s2.size(), s2 );
52
53 if ( f == 0 )
54 cout << "z1.compare( 0, s2.size(), s2 ) == 0" << endl;
55 else if ( f > 0 )
56 cout << "z1.compare( 0, s2.size(), s2 ) > 0" << endl;
57 else // f < 0
58 cout << "z1.compare( 0, s2.size(), s2 ) < 0" << endl;
59
60 return 0;
61 }
s1.compare( s2 ) > 0
s1.compare( 2, 5, s3, 0, 5 ) == 0
z1.compare( 0, s2.size(), s2 ) == 0
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
Program Output
s1: Testing the comparison functions.s2: Hellos3: stingerz1: Hello s1 > z1s1.compare( s2 ) > 0s1.compare( 2, 5, s3, 0, 5 ) == 0z1.compare( 0, s2.size(), s2 ) == 0
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.4Substrings
• Function substr retrieves a substring from a string.
s1.substr( startSubScript, number );
– startSubscript - starting subscript– number - number of characters to extract
– returns the substring
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.5Swapping strings
• Function swap swaps the contents of two strings.
s1.swap(s2);– switches s1 and s2
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.6string Characteristics
• s1.size() and s1.length()– current number of characters in string
• s1.capacity() – number of elements that can be stored without reallocation
• s1.max_size() – maximum possible string size
• str.empty() – if no characters, returns true
• s1.resize(newlength)– resizes string to newlength
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
1. Initialize string
2. Function calls
3. Output
1 // Fig. 19.5: fig19_05.cpp2 // Demonstrating functions related to size and capacity3 #include <iostream>45 using std::cout;6 using std::endl;7 using std::cin;89 #include <string>1011 using std::string;1213 void printStats( const string & );1415 int main()16 {17 string s;18 19 cout << "Stats before input:\n";20 printStats( s );2122 cout << "\n\nEnter a string: ";23 cin >> s; // delimited by whitespace24 cout << "The string entered was: " << s;2526 cout << "\nStats after input:\n";27 printStats( s );2829 s.resize( s.length() + 10 );30 cout << "\n\nStats after resizing by (length + 10):\n";31 printStats( s );3233 cout << endl;
Stats before input:
capacity: 0
max size: 4294967293
size: 0
length: 0
empty: true
Enter a string: tomato soup
The string entered was: tomato
Stats after input:
capacity: 31
max size: 4294967293
size: 6
length: 6
empty: false
Stats after resizing by (length + 10):
capacity: 31
max size: 4294967293
size: 16
length: 16
empty: false
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
3.1 Function definition
Program Output
34 return 0;
35 }
36
37 void printStats( const string &str )
38 {
39 cout << "capacity: " << str.capacity()
40 << "\nmax size: " << str.max_size()
41 << "\nsize: " << str.size()
42 << "\nlength: " << str.length()
43 << "\nempty: " << ( str.empty() ? "true": "false" );
44 }
Stats before input:capacity: 0max size: 4294967293size: 0length: 0empty: true Enter a string: tomato soupThe string entered was: tomatoStats after input:capacity: 31max size: 4294967293size: 6length: 6empty: false Stats after resizing by (length + 10):capacity: 31max size: 4294967293size: 16length: 16empty: false
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.7Finding Characters in a string
• Class string find functions: – if found, subscript of match returned
– if not found, value of string::npos is returned
– s1.find(string) - searches s1 for string– s1.rfind(string) - like find, but searches s1 for
string backwards.
– s1.find_first_of(string) - finds first occurrence in s1 of any character in string
– s1.find_last_of(string)- as above, but last occurrence. Searches s1 backwards.
– s1.find_first_not_of(string)- finds first character in s1 NOT in s2.
– s1.find_last_not_of(string) - as above, but last character. Searches s1 backwards.
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
1. Initialize string
2. Function calls
3. Output
1 // Fig. 19.6: fig19_06.cpp2 // Demonstrating the string find functions3 #include <iostream>45 using std::cout;6 using std::endl;78 #include <string>910 using std::string;1112 int main()13 {14 // compiler concatenates all parts into one string literal15 string s( "The values in any left subtree"16 "\nare less than the value in the"17 "\nparent node and the values in"18 "\nany right subtree are greater"19 "\nthan the value in the parent node" );20 21 // find "subtree" at locations 23 and 10222 cout << "Original string:\n" << s 23 << "\n\n(find) \"subtree\" was found at: " 24 << s.find( "subtree" ) 25 << "\n(rfind) \"subtree\" was found at: " 26 << s.rfind( "subtree" );2728 // find 'p' in parent at locations 62 and 14429 cout << "\n(find_first_of) character from \"qpxz\" at: " 30 << s.find_first_of( "qpxz" ) 31 << "\n(find_last_of) character from \"qpxz\" at: " 32 << s.find_last_of( "qpxz" );33
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
(find) "subtree" was found at: 23
(rfind) "subtree" was found at: 102
(find_first_of) character from "qpxz" at: 62
(find_last_of) character from "qpxz" at: 144
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
3. Output
Program Output
34 // find 'b' at location 25
35 cout << "\n(find_first_not_of) first character not\n"
36 << " contained in \"heTv lusinodrpayft\": "
37 << s.find_first_not_of( "heTv lusinodrpayft" );
38
39 // find '\n' at location 121
40 cout << "\n(find_last_not_of) first character not\n"
41 << " contained in \"heTv lusinodrpayft\": "
42 << s.find_last_not_of( "heTv lusinodrpayft" ) << endl;
43
44 return 0;
45 }
Original string:The values in any left subtreeare less than the value in theparent node and the values inany right subtree are greaterthan the value in the parent node (find) "subtree" was found at: 23(rfind) "subtree" was found at: 102(find_first_of) character from "qpxz" at: 62(find_last_of) character from "qpxz" at: 144(find_first_not_of) first character not contained in "heTv lusinodrpayft": 25(find_last_not_of) first character not contained in "heTv lusinodrpayft": 121
(find_first_not_of) first character not
contained in "heTv lusinodrpayft": 25
(find_last_not_of) first character not
contained in "heTv lusinodrpayft": 121
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.8Replacing Characters in a string
• s1.erase(number);– erases everything after element number to the end
• s1.replace(sub1, numberToReplace, replacementString, sub2, numberToUse);
– sub1 - subscript in s1 where replacement occurs– numberToReplace - number of characters being replaced in s1,
starting from sub1– replacementString - string containing replacement characters– sub2 - beginning subscript of replacement characters in
replacementString– numberToUse - number of replacement characters to use in
replacementString, starting with sub2
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
1. Initialize string
2. Function calls
3. Output
1 // Fig. 19.7: fig19_07.cpp2 // Demonstrating functions erase and replace3 #include <iostream>45 using std::cout;6 using std::endl;78 #include <string>910 using std::string;1112 int main()13 {14 // compiler concatenates all parts into one string15 string s( "The values in any left subtree"16 "\nare less than the value in the"17 "\nparent node and the values in"18 "\nany right subtree are greater"19 "\nthan the value in the parent node" );20 21 // remove all characters from location 62 22 // through the end of s23 s.erase( 62 );2425 // output the new string26 cout << "Original string after erase:\n" << s 27 << "\n\nAfter first replacement:\n";28 29 // replace all spaces with a period30 int x = s.find( " " );31 while ( x < string::npos ) {32 s.replace( x, 1, "." );33 x = s.find( " ", x + 1 );
Original string after erase:
The values in any left subtree
are less than the value in the
Remove all characters from location 62 (the 63rd element) to the end.
After first replacement:
The.values.in.any.left.subtree
are.less.than.the.value.in.the
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
3. Output
Program Output
34 }
35
36 cout << s << "\n\nAfter second replacement:\n";
37
38 // replace all periods with two semicolons
39 // NOTE: this will overwrite characters
40 x = s.find( "." );
41 while ( x < string::npos ) {
42 s.replace( x, 2, "xxxxx;;yyy", 5, 2 );
43 x = s.find( ".", x + 1 );
44 }
45
46 cout << s << endl;
47 return 0;
48 }
Original string after erase:The values in any left subtreeare less than the value in the After first replacement:The.values.in.any.left.subtreeare.less.than.the.value.in.the After second replacement:The;;alues;;n;;ny;;eft;;ubtreeare;;ess;;han;;he;;alue;;n;;he
After second replacement:
The;;alues;;n;;ny;;eft;;ubtree
are;;ess;;han;;he;;alue;;n;;he
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.9Inserting Characters into a string
• s1.insert(sub1, string)– inserts string before element sub1 in s1
• s1.insert(sub1, string, sub2, numChars);– selects numChars characters, starting from sub2 in string, and
inserts them into s1.
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.10 Conversion to C-Style char * Strings
• strings can be converted to C-style char * strings– s1.data() - conversion to const char * string, not
null terminated– s1.c_str() - conversion to const char * string, null
terminated (ends with '\0')
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
1. Initialize strings
2. Insert strings
3. Print results.
1 // Fig. 19.9: fig19_09.cpp2 // Converting to C-style strings.3 #include <iostream>45 using std::cout;6 using std::endl;78 #include <string>910 using std::string;1112 int main()13 {14 string s( "STRINGS" );15 const char *ptr1 = 0;16 int len = s.length();17 char *ptr2 = new char[ len + 1 ]; // including null18 19 // copy characters out of string into allocated memory20 s.copy( ptr2, len, 0 );21 ptr2[ len ] = 0; // add null terminator2223 // output 24 cout << "string s is " << s 25 << "\ns converted to a C-Style string is "26 << s.c_str() << "\nptr1 is ";2728 // Assign to pointer ptr1 the const char * returned by29 // function data(). NOTE: this is a potentially dangerous30 // assignment. If the string is modified, the pointer31 // ptr1 can become invalid.32 ptr1 = s.data(); 33
Notice the format for inserting strings.
string s is STRINGS
s converted to a C-Style string is STRINGS
ptr1 is STRINGS
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
3. Print results.
Program Output
34 for ( int k = 0; k < len; ++k )
35 cout << *( ptr1 + k ); // use pointer arithmetic
36
37 cout << "\nptr2 is " << ptr2 << endl;
38 delete [] ptr2;
39 return 0;
40 }
string s is STRINGSs converted to a C-Style string is STRINGSptr1 is STRINGSptr2 is STRINGS
ptr2 is STRINGS
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.11 Iterators
• iterators– forwards and backwards traversal of strings
– access to individual characters
– similar to pointer operations
• Basic coverage here - more next chapter– type const_iterator - iterator that cannot modify the string– s.begin() - returns iterator to front of string– s.end() - returns iterator to end– *myIterator - dereferences iterator (like pointer)– ++myIterator - advances iterator one position (character)
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
19.12 String Stream Processing
• in-memory I/O (string stream processing)– headers <sstream> and <iostream>
• Inputting strings to memory– create objects of class istringstream
istringstream myInputString;– works the same as input from a file
– can feed input string into other strings
• Output to a string– objects of class ostringstream
ostringstream myOutputString;
- myOutputString.str() - outputs the string
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
1. Initialize ostringstream object
1.1 Initialize strings
1.2 Initialize variables
2. Print outputString
2.1 Modify outputString
1 // Fig. 19.11: fig19_11.cpp
2 // Using a dynamically allocated ostringstream object.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <string>
9
10 using std::string;
11
12 #include <sstream>
13
14 using std::ostringstream;
15
16 int main()
17 {
18 ostringstream outputString;
19 string s1( "Output of several data types " ),
20 s2( "to an ostringstream object:" ),
21 s3( "\n double: " ),
22 s4( "\n int: " ),
23 s5( "\naddress of int: " );
24 double d = 123.4567;
25 int i = 22;
26
27 outputString << s1 << s2 << s3 << d << s4 << i << s5 << &i;
28 cout << "outputString contains:\n" << outputString.str();
29
30 outputString << "\nmore characters added";
output strings to outputString
outputString contains:
Output of several data types to an ostringstream object:
double: 123.457
int: 22
address of int: 0068FD0C
Add more characters to outputString
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
2.2 Print outputString
Program Output
31 cout << "\n\nafter additional stream insertions,\n"
32 << "outputString contains:\n" << outputString.str()
33 << endl;
34
35 return 0;
36 }
outputString contains:Output of several data types to an ostringstream object: double: 123.457 int: 22address of int: 0068FD0C after additional stream insertions,outputString contains:Output of several data types to an ostringstream object: double: 123.457 int: 22address of int: 0068FD0Cmore characters added
after additional stream insertions,
outputString contains:
Output of several data types to an ostringstream object:
double: 123.457
int: 22
address of int: 0068FD0C
more characters added
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
1. Initialize objects
2. Input data into string1 and string2
1 // Fig. 19.12: fig19_12.cpp2 // Demonstrating input from an istringstream object.3 #include <iostream>45 using std::cout;6 using std::endl;78 #include <string>910 using std::string;1112 #include <sstream>1314 using std::istringstream;1516 int main()17 {18 string input( "Input test 123 4.7 A" );19 istringstream inputString( input );20 string string1, string2;21 int i;22 double d;23 char c;2425 inputString >> string1 >> string2 >> i >> d >> c;2627 cout << "The following items were extracted\n"28 << "from the istringstream object:"29 << "\nstring: " << string1 30 << "\nstring: " << string2 31 << "\n int: " << i 32 << "\ndouble: " << d 33 << "\n char: " << c;
Notice how inputString inputs data to string1 and string2 (similar format as cin)
The following items were extracted
from the istringstream object:
String: Input
String: test
int: 123
double: 4.7
char: A
2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.
Outline
2. Function calls
Program Output
34
35 // attempt to read from empty stream
36 long x;
37
38 inputString >> x;
39
40 if ( inputString.good() )
41 cout << "\n\nlong value is: " << x << endl;
42 else
43 cout << "\n\ninputString is empty" << endl;
44
45 return 0;
46 }
The following items were extractedfrom the istringstream object:String: InputString: test int: 123double: 4.7 char: AinputString is empty
inputString is empty