0% found this document useful (0 votes)
21 views

2003 Prentice Hall, Inc. All Rights Reserved

This document summarizes Chapter 15 of a textbook on C++ string and string stream processing. It outlines sections on string assignment and concatenation, comparing strings, substrings, swapping strings, string characteristics, finding/replacing characters in strings, and inserting characters. It provides examples of initializing strings, assigning strings, comparing strings using operators and member functions, and concatenating strings using assignment, append, and overloaded operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

2003 Prentice Hall, Inc. All Rights Reserved

This document summarizes Chapter 15 of a textbook on C++ string and string stream processing. It outlines sections on string assignment and concatenation, comparing strings, substrings, swapping strings, string characteristics, finding/replacing characters in strings, and inserting characters. It provides examples of initializing strings, assigning strings, comparing strings using operators and member functions, and concatenating strings using assignment, append, and overloaded operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 52

1

Chapter 15 - Class string and String


Stream Processing
Outline
15.1 Introduction
15.2 string Assignment and Concatenation
15.3 Comparing strings
15.4 Substrings
15.5 Swapping strings
15.6 string Characteristics
15.7 Finding Strings and Characters in a string
15.8 Replacing Characters in a string
15.9 Inserting Characters into a string
15.10 Conversion to C-Style char * Strings
15.11 Iterators
15.12 String Stream Processing

 2003 Prentice Hall, Inc. All rights reserved.


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 s1( "Hello" );
– string s2( 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 error1 = 'c';
• string error2( 'u' );
• string error3 = 22;
• string error4( 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: s1.length()
– Use [] to access individual characters: s1[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 >> stringObject;
• getline( cin, s)
– Delimited by newline

 2003 Prentice Hall, Inc. All rights reserved.


5

15.2 string Assignment and Concatenation

• Assignment
– s2 = s1;
• Makes a separate copy
– s2.assign(s1);
• Same as s2 = s1;
– myString.assign(s, start, N);
• Copies N characters from s, beginning at index start
– Individual characters
• s2[0] = s3[2];

 2003 Prentice Hall, Inc. All rights reserved.


6

15.2 string Assignment and Concatenation

• Range checking
– s3.at( index );
• Returns character at index
• Can throw out_of_range exception
– [] has no range checking
• Concatenation
– s3.append( "pet" );
– s3 += "pet";
• Both add "pet" to end of s3
– s3.append( s1, start, N );
• Appends N characters from s1, beginning at index start

 2003 Prentice Hall, Inc. All rights reserved.


7
1 // Fig. 15.1: fig15_01.cpp
2 // Demonstrating string assignment and concatenation.
Outline
3 #include <iostream>
4
fig15_01.cpp
5 using std::cout;
(1 of 3)
6 using std::endl;
7
8 #include <string>
9
10 using std::string;
11
String initialization and
12 int main() assignment.
13 {
14 string string1( "cat" );
Output
15 string string2;
string1: cat
16 string string3;
string2: cat
17
string3: cat
18 string2 = string1; // assign string1 to string2
19 string3.assign( string1 ); // assign string1 to string3
20 cout << "string1: " << string1 << "\nstring2: " << string2
21 << "\nstring3: " << string3 << "\n\n";
22

 2003 Prentice Hall, Inc.


All rights reserved.
8
23 // modify string2 and string3
24 string2[ 0 ] = string3[ 2 ] = 'r';
Outline
25
26 cout << "After modification of string2 and string3:\n"
fig15_01.cpp
27 << "string1: " << string1 << "\nstring2: " << string2
(2 of 3)
28 << "\nstring3: ";
29
30 // demonstrating member function at After modification of string2 and string3:
31 string1:
for ( int i = 0; i < string3.length(); i++ ) cat
32 cout << string3.at( i ); string2: rat
33 string3: car
34 // declare string4 and string5
35 string string4( string1 + "apult" );
Note use of member function
36 string string5;
at instead of [].
37
38 // overloaded +=
39 string3 += "pet"; // create "carpet" After concatenation:
40 string1.append( "acomb" ); // create "catacomb" string1: catacomb
41 string2: rat
42 // append subscript locations 4 through end of string1 to
string3: carpet
43 // create string "comb" (string5 was initially empty) string4: catapult
44 string5.append( string1, 4, string1.length() ); string5: comb
45
46 cout << "\n\nAfter concatenation:\nstring1: " << string1
47 << "\nstring2: " << string2 << "\nstring3: "
48 << string3 << "\nstring4: " << string4
49 << "\nstring5: " << string5 << endl;
50
 2003 Prentice Hall, Inc.
All rights reserved.
9
51 return 0;
52 Outline
53 } // end main

string1: cat
fig15_01.cpp
string2: cat (3 of 3)
string3: cat
  fig15_01.cpp
After modification of string2 and string3: output (1 of 1)
string1: cat
string2: rat
string3: car
 
After concatenation:
string1: catacomb
string2: rat
string3: carpet
string4: catapult
string5: comb

 2003 Prentice Hall, Inc.


All rights reserved.
10

15.3 Comparing strings

• Overloaded operators
– ==, !=, <, >, <= and >=
– Return bool
• s1.compare(s2)
– Returns positive if s1 lexicographically greater
• Compares letter by letter
• 'B' lexicographically greater than 'A'
– Returns negative if less, zero if equal
– s1.compare(start, length, s2, start,
length)
• Compare portions of s1 and s2
– s1.compare(start, length, s2)
• Compare portion of s1 with all of s2
 2003 Prentice Hall, Inc. All rights reserved.
11
1 // Fig. 15.2: fig15_02.cpp
2 // Demonstrating string comparison capabilities.
Outline
3 #include <iostream>
4
fig15_02.cpp
5 using std::cout;
(1 of 4)
6 using std::endl;
7
8 #include <string>
9
10 using std::string;
11
12 int main()
13 {
14 string string1( "Testing the comparison functions." );
15 string string2( "Hello" );
16 string string3( "stinger" );
17 string string4( string2 );
18

 2003 Prentice Hall, Inc.


All rights reserved.
12
19 cout << "string1: " << string1 << "\nstring2: " << string2
20 << "\nstring3: " << string3 << "\nstring4: " << string4
Outline
21 << "\n\n";
22 Note use of overloaded ==
operator. fig15_02.cpp
23 // comparing string1 and string4
(2 of 4)
24 if ( string1 == string4 )
25 cout << "string1 == string4\n"; string1: Testing the comparison functions.
26 else { // string1 != string4 string2: Hello
27 if ( string1 > string4 ) string3: stinger
28 cout << "string1 > string4\n"; string4: Hello
29 else // string1 < string4  
30 cout << "string1 < string4\n"; string1 > string4
31 }
32
33 // comparing string1 and string2
34 int result = string1.compare( string2 );
35
36 if ( result == 0 )
37 cout << "string1.compare( string2 ) == 0\n";
38 else // result != 0
39 if ( result > 0 )
40 cout << "string1.compare( string2 ) > 0\n";
41 else // result < 0
42 cout << "string1.compare( string2 ) < 0\n";
43

 2003 Prentice Hall, Inc.


All rights reserved.
13
44 // comparing string1 (elements 2-5) and string3 (elements 0-5)
45 result = string1.compare( 2, 5, string3, 0, 5 );
Outline
46
47 if ( result == 0 )
Note use of compare.
fig15_02.cpp
48 cout << "string1.compare( 2, 5, string3, 0, 5 ) == 0\n";
(3 of 4)
49 else // result != 0
50 if ( result > 0 )
51 cout << "string1.compare( 2, 5, string3, 0, 5 ) > 0\n";
52 else // result < 0
53 cout << "string1.compare( 2, 5, string3, 0, 5 ) < 0\n";
54
55 // comparing string2 and string4
56 result = string4.compare( 0, string2.length(), string2 );
57
58 if ( result == 0 )
59 cout << "string4.compare( 0, string2.length(), "
60 << "string2 ) == 0" << endl;
61 else // result != 0
62 if ( result > 0 )
63 cout << "string4.compare( 0, string2.length(), "
64 << "string2 ) > 0" << endl;
65 else // result < 0
66 cout << "string4.compare( 0, string2.length(), "
67 << "string2 ) < 0" << endl;
68

 2003 Prentice Hall, Inc.


All rights reserved.
14
69 // comparing string2 and string4
70 result = string2.compare( 0, 3, string4 );
Outline
71
72 if ( result == 0 )
fig15_02.cpp
73 cout << "string2.compare( 0, 3, string4 ) == 0" << endl;
(4 of 4)
74 else // result != 0
75 if ( result > 0 )
76 cout << "string2.compare( 0, 3, string4 ) > 0" << endl; fig15_02.cpp
77 else // result < 0 output (1 of 1)
78 cout << "string2.compare( 0, 3, string4 ) < 0" << endl;
79
80 return 0;
81
82 } // end main

string1: Testing the comparison functions.


string2: Hello
string3: stinger
string4: Hello
 
string1 > string4
string1.compare( string2 ) > 0
string1.compare( 2, 5, string3, 0, 5 ) == 0
string4.compare( 0, string2.length(), string2 ) == 0
string2.compare( 0, 3, string4 ) < 0

 2003 Prentice Hall, Inc.


All rights reserved.
15

15.4 Substrings

• Function substr gets substring


– s1.substr( start, N );
– Gets N characters, beginning with index start
– Returns substring

 2003 Prentice Hall, Inc. All rights reserved.


16
1 // Fig. 15.3: fig15_03.cpp
2 // Demonstrating string member function substr.
Outline
3 #include <iostream>
4
fig15_03.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <string> fig15_03.cpp
9 output (1 of 1)
10 using std::string;
11
12 int main()
13 {
14 string string1( "The airplane landed on time." );
15 Note usage of substr.
16 // retrieve substring "plane" which
17 // begins at subscript 7 and consists of 5 elements
18 cout << string1.substr( 7, 5 ) << endl;
19
20 return 0;
21
22 } // end main

plane

 2003 Prentice Hall, Inc.


All rights reserved.
17

15.5 Swapping strings

• s1.swap(s2);
– Switch contents of two strings

 2003 Prentice Hall, Inc. All rights reserved.


18
1 // Fig. 15.4: fig15_04.cpp
2 // Using the swap function to swap two strings.
Outline
3 #include <iostream>
4
fig15_04.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <string>
9
10 using std::string;
11
12 int main()
13 {
14 string first( "one" );
15 string second( "two" );
16
17 // output strings
18
Call swap.
cout << "Before swap:\n first: " << first
19 << "\nsecond: " << second;
20
21 first.swap( second ); // swap strings
22
23 cout << "\n\nAfter swap:\n first: " << first
24 << "\nsecond: " << second << endl;
25
26 return 0;
27
28 } // end main
 2003 Prentice Hall, Inc.
All rights reserved.
19
Before swap:
first: one
Outline
second: two
 
fig15_04.cpp
After swap:
output (1 of 1)
first: two
second: one

 2003 Prentice Hall, Inc.


All rights reserved.
20

15.6 string Characteristics

• Member functions
– s1.size() and s1.length()
• Number of characters in string
– s1.capacity()
• Number of elements that can be stored without reallocation
– s1.max_size()
• Maximum possible string size
– s1.empty()
• Returns true if empty
– s1.resize(newlength)
• Resizes string to newlength

 2003 Prentice Hall, Inc. All rights reserved.


21
1 // Fig. 15.5: fig15_05.cpp
2 // Demonstrating member functions related to size and capacity.
Outline
3 #include <iostream>
4
fig15_05.cpp
5 using std::cout;
(1 of 3)
6 using std::endl;
7 using std::cin;
8 using std::boolalpha;
9
10 #include <string>
11
12 using std::string;
13
14 void printStatistics( const string & );
15
16 int main()
17 {
18 string string1;
19
20 cout << "Statistics before input:\n" << boolalpha;
21 printStatistics( string1 );
22
23 // read in "tomato"
24 cout << "\n\nEnter a string: ";
25 cin >> string1; // delimited by whitespace
26 cout << "The string entered was: " << string1;

 2003 Prentice Hall, Inc.


All rights reserved.
22
27
28 cout << "\nStatistics after input:\n";
Outline
29 printStatistics( string1 );
30
fig15_05.cpp
31 // read in "soup"
(2 of 3)
32 cin >> string1; // delimited by whitespace
33 cout << "\n\nThe remaining string is: " << string1 << endl;
34 printStatistics( string1 );
35
36 // append 46 characters to string1
37 string1 += "1234567890abcdefghijklmnopqrstuvwxyz1234567890";
38 cout << "\n\nstring1 is now: " << string1 << endl;
Resize string.
39 printStatistics( string1 );
40
41 // add 10 elements to string1
42 string1.resize( string1.length() + 10 );
43 cout << "\n\nStats after resizing by (length + 10):\n";
44 printStatistics( string1 );
45
46 cout << endl;
47 return 0;
48
49 } // end main
50

 2003 Prentice Hall, Inc.


All rights reserved.
23
51 // display string statistics Display various string
52 void printStatistics( const string &stringRef )
Outline
characteristics.
53 {
54 cout << "capacity: " << stringRef.capacity()
fig15_05.cpp
55 << "\nmax size: " << stringRef.max_size()
(3 of 3)
56 << "\nsize: " << stringRef.size()
57 << "\nlength: " << stringRef.length()
58 << "\nempty: " << stringRef.empty(); fig15_05.cpp
59 output (1 of 2)
60 } // end printStatistics

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
max size: 4294967293
size: 6
length: 6
empty: false

 2003 Prentice Hall, Inc.


All rights reserved.
24
The remaining string is: soup
capacity: 31
Outline
max size: 4294967293
size: 4
fig15_05.cpp
length: 4
output (2 of 2)
empty: false

string1 is now: soup1234567890abcdefghijklmnopqrstuvwxyz1234567890


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

 2003 Prentice Hall, Inc.


All rights reserved.
25

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
– s1.find( s2 )
– s1.rfind( s2 )
• Searches right-to-left
– s1.find_first_of( s2 )
• Returns first occurrence of any character in s2
• s1.find_frist_of( "abcd" )
– Returns index of first 'a', 'b', 'c' or 'd'

 2003 Prentice Hall, Inc. All rights reserved.


26

15.7 Finding Strings and Characters in a string

• Find functions
– s1.find_last_of( s2 )
• Finds last occurrence of any character in s2
– s1.find_first_not_of( s2 )
• Finds first character NOT in s2
– s1.find_last_not_of( s2 )
• Finds last character NOT in s2

 2003 Prentice Hall, Inc. All rights reserved.


27
1 // Fig. 15.6: fig15_06.cpp
2 // Demonstrating the string find member functions
Outline
3 #include <iostream>
4
fig15_06.cpp
5 using std::cout;
(1 of 3)
6 using std::endl;
7
8 #include <string>
9
10 using std::string;
11
12 int main()
13 {
14 string string1( "noon is 12 p.m." );
15 int location;
16
Note call to function find.
17 // find "is" at location 5
18 cout << "Original string:\n" << string1
19 << "\n\n(find) \"is\" was found at: "
20 << string1.find( "is" )
21 << "\n(rfind) \"is\" was found at: "
Find first occurrence of m, i,
22 << string1.rfind( "is" );
s, o or p.
23
24 // find 'o' at location 1
25 location = string1.find_first_of( "misop" );

 2003 Prentice Hall, Inc.


All rights reserved.
28
26
27 cout << "\n\n(find_first_of) found '" << string1[ location ]
Outline
28 << "' from the group \"misop\" at: "
29 << location; Calls to other find functions
similar. fig15_06.cpp
30
(2 of 3)
31 // find 'm' at location 13
32 location = string1.find_last_of( "misop" );
33 cout << "\n\n(find_last_of) found '" << string1[ location ]
34 << "' from the group \"misop\" at: "
35 << location;
36
37 // find '1' at location 8
38 location = string1.find_first_not_of( "noi spm" );
39 cout << "\n\n(find_first_not_of) '" << string1[ location ]
40 << "' is not contained in \"noi spm\" and was found at:"
41 << location;
42
43 // find '.' at location 12
44 location = string1.find_first_not_of( "12noi spm" );
45 cout << "\n\n(find_first_not_of) '" << string1[ location ]
46 << "' is not contained in \"12noi spm\" and was "
47 << "found at:" << location << endl;

 2003 Prentice Hall, Inc.


All rights reserved.
29
48
49 // search for characters not in string1
Outline
50 location = string1.find_first_not_of( "noon is 12 p.m." );
51 cout << "\nfind_first_not_of(\"noon is 12 p.m.\")"
fig15_06.cpp
52 << " returned: " << location << endl;
(3 of 3)
53
54 return 0;
55 fig15_06.cpp
56 } // end main output (1 of 1)

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
 
(find_first_not_of) '.' is not contained in "12noi spm" and was found
at:12
 
find_first_not_of("noon is 12 p.m.") returned: -1

 2003 Prentice Hall, Inc.


All rights reserved.
30

15.8 Replacing Characters in a string

• s1.erase( start )
– Erase from index start to end of string, including start
• Replace
– s1.replace( begin, N, s2)
• begin: index in s1 to start replacing
• N: number of characters to replace
• s2: replacement string
– s1.replace( begin, N, s2, index, num )
• index: element in s2 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.


31
1 // Fig. 15.7: fig15_07.cpp
2 // Demonstrating string member functions erase and replace.
Outline
3 #include <iostream>
4
fig15_07.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <string>
9
10 using std::string;
11
12 int main()
13 {
14 // compiler concatenates all parts into one string
15 string string1( "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 cout << "Original string:\n" << string1 << endl << endl;
22
23 // remove all characters from (and including) location 62
24 // through the end of string1
25 string1.erase( 62 );
26

 2003 Prentice Hall, Inc.


All rights reserved.
32
27 // output new string
28
string::npos represents
cout << "Original string after erase:\n" << string1
Outline
29 max string length.
<< "\n\nAfter first replacement:\n";
30
fig15_07.cpp
31 // replace all spaces with period
Find each space and
(2replace
of 2)
32 int position = string1.find( " " );
33
with a '.'
34 while ( position != string::npos ) {
35 string1.replace( position, 1, "." );
36 position = string1.find( " ", position + 1 );
37 } // end while
38
39 cout << string1 << "\n\nAfter second replacement:\n";
Start each search at the next
40
position.
41 // replace all periods with two semicolons
42 // NOTE: this will overwrite characters
Replace all '.' with two
43 position = string1.find( "." );
44
semicolons (the two
45 while ( position != string::npos ) { characters at index 5).
46 string1.replace( position, 2, "xxxxx;;yyy", 5, 2 );
47 position = string1.find( ".", position + 1 );
48 } // end while
49
50 cout << string1 << endl;
51 return 0;
52
53 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
33
Original string:
The values in any left subtree
Outline
are less than the value in the
parent node and the values in
fig15_07.cpp
any right subtree are greater
output (1 of 1)
than the value in the parent node
 
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
 
 
After second replacement:
The;;alues;;n;;ny;;eft;;ubtree
are;;ess;;han;;he;;alue;;n;;he

 2003 Prentice Hall, Inc.


All rights reserved.
34

15.9 Inserting Characters into a string

• s1.insert( index, s2 )
– Inserts s2 before position index
• s1.insert( index, s2, index2,
N );
– Inserts substring of s2 before position index
– Substring is N characters, starting at index2

 2003 Prentice Hall, Inc. All rights reserved.


35
1 // Fig. 15.8: fig15_08.cpp
2 // Demonstrating class string insert member functions.
Outline
3 #include <iostream>
4
fig15_08.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <string>
9
10 using std::string;
11
12 int main()
13 {
14 string string1( "beginning end" );
15 string string2( "middle " );
16 string string3( "12345678" );
17 string string4( "xx" );
18
19 cout << "Initial strings:\nstring1: " << string1
20 << "\nstring2: " << string2 << "\nstring3:
Insert all" of
<<string2
string3 before
21 << "\nstring4: " << string4 << "\n\n";
element 10.
22
23 // insert "middle" at location 10 in string1
24 string1.insert( 10, string2 );
25

 2003 Prentice Hall, Inc.


All rights reserved.
36
26 // insert "xx" at location 3 in string3
27 string3.insert( 3, string4, 0, string::npos );
Outline
28
29 cout << "Strings after insert:\nstring1: " << string1
fig15_08.cpp
30 << "\nstring2: " << string2 << "\nstring3: " << string3
(2 of 2)
31 << "\nstring4: " << string4 << endl;
32
33 return 0; Insert all of string4 before fig15_08.cpp
34 index 3. output (1 of 1)
35 } // end main

Initial strings:
string1: beginning end
string2: middle
string3: 12345678
string4: xx
 
Strings after insert:
string1: beginning middle end
string2: middle
string3: 123xx45678
string4: xx

 2003 Prentice Hall, Inc.


All rights reserved.
37

15.10 Conversion to C-Style char * Strings

• Conversion functions
– strings not necessarily null-terminated
– s1.copy( ptr, N, index )
• Copies N characters into the array ptr
• Starts at location index
• Need to null terminate
– s1.c_str()
• Returns const char *
• Null terminated
– s1.data()
• Returns const char *
• NOT null-terminated

 2003 Prentice Hall, Inc. All rights reserved.


38
1 // Fig. 15.9: fig15_09.cpp
2 // Converting to C-style strings.
Outline
3 #include <iostream>
4
fig15_09.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <string>
9
10 using std::string;
11
12 int main()
13 {
Note calls to copy and
14 string string1( "STRINGS" );
c_str.
15 const char *ptr1 = 0;
16 int length = string1.length();
17 char *ptr2 = new char[ length + 1 ]; // including null
18
19 // copy characters from string1 into allocated memory
20 string1.copy( ptr2, length, 0 );
21 ptr2[ length ] = '\0'; // add null terminator
22
23 // output
24 cout << "string s is " << string1
25 << "\nstring1 converted to a C-Style string is "
26 << string1.c_str() << "\nptr1 is ";

 2003 Prentice Hall, Inc.


All rights reserved.
39
27
28 // Assign to pointer ptr1 the const char * returned by
Outline
29 // function data(). NOTE: this is a potentially dangerous
30 // assignment. If string1 is modified, pointer ptr1 can
fig15_09.cpp
31 // become invalid.
(2 of 2)
32 ptr1 = string1.data();
33
34 // output each character using pointer fig15_09.cpp
35 for ( int i = 0; i < length; i++ ) output (1 of 1)
36 cout << *( ptr1 + i ); // use pointer arithmetic
37
38 cout << "\nptr2 is " << ptr2 << endl;
39 delete [] ptr2;
40 return 0;
41
42 } // end main

string s is STRINGS
string1 converted to a C-Style string is STRINGS
ptr1 is STRINGS
ptr2 is STRINGS

 2003 Prentice Hall, Inc.


All rights reserved.
40

15.11 Iterators

• Iterators
– Forwards and backwards traversal of strings
– Access to individual characters
– Similar to pointer operations
– More coverage Chapter 20

 2003 Prentice Hall, Inc. All rights reserved.


41

15.11 Iterators

• Basic usage
– Creation
• string::const_iterator i = s.begin();
• const, cannot modify string (more Chapter 20)
– Referencing
• *i; // reference character
• ++i; // traverse one character forward
– Test for end of string
• i != s.end()
• end returns iterator after last element of s

 2003 Prentice Hall, Inc. All rights reserved.


42
1 // Fig. 15.10: fig15_10.cpp
2 // Using an iterator to output a string.
Outline
3 #include <iostream>
4
fig15_10.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <string>
9
10 using std::string;
11
12 int main()
13 {
14 string string1( "Testing iterators" );
15 string::const_iterator iterator1 = string1.begin();
16
17 cout << "string1 = " << string1 Print each character using the
18 << "\n(Using iterator iterator1) string1iterator.
is: ";
19
20 // iterate through string
21 while ( iterator1 != string1.end() ) {
22 cout << *iterator1; // dereference iterator to get char
23 ++iterator1; // advance iterator to next char
24 } // end while
25
26 cout << endl;
27 return 0;
28
29 } // end main  2003 Prentice Hall, Inc.
All rights reserved.
43
string1 = Testing iterators
(Using iterator iterator1) string1 is: Testing iterators
Outline

fig15_10.cpp
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
44

15.12 String Stream Processing

• I/O of strings to and from memory


– Called in-memory I/O or string stream processing
– Classes
• istringstream (input from string)
• ostringstream (output to a string)
• <sstream> and <iostream> headers
– Use string formatting to save data to memory

 2003 Prentice Hall, Inc. All rights reserved.


45

15.12 String Stream Processing

• String output
– Ostringstream outputString;
– outputString << s1 << s2;
– Member function str
• Returns string that was output to memory
• outputString.str()

 2003 Prentice Hall, Inc. All rights reserved.


46
1 // Fig. 15.11: fig15_11.cpp
2 // Using a dynamically allocated ostringstream object.
Outline
3 #include <iostream>
4
fig15_11.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <string>
9
10 using std::string;
11
12 #include <sstream>
13
14 using std::ostringstream; Create ostringstream
15 object.
16 int main()
17 {
18 ostringstream outputString; // create ostringstream instance
19
20 string string1( "Output of several data types " );
21 string string2( "to an ostringstream object:" );
22 string string3( "\n double: " );
23 string string4( "\n int: " );
24 string string5( "\naddress of int: " );

 2003 Prentice Hall, Inc.


All rights reserved.
47
25
26 double double1 = 123.4567;
Outline
27 int integer = 22;
28
fig15_11.cpp
29 // output strings, double and int to outputString
(2 of 2)
30 outputString << string1 << string2 << string3 << double1
31 << string4 << integer << string5 << &integer;
32
33 // call str to output contents
34 cout << "outputString contains:\n" << outputString.str();
35
36 // add additional characters and call str to output string
37 outputString << "\nmore characters added";
Output format just like to
38 cout << "\n\nafter additional stream insertions,\n"
writing to cout.
39 << "outputString contains:\n" << outputString.str()
40 << endl;
41
42 return 0;
43
44 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
48
outputString contains:
Output of several data types to an ostringstream object:
Outline
double: 123.457
int: 22
fig15_11.cpp
address of int: 0012FE94
output (1 of 1)
 
after additional stream insertions,
outputString contains:
Output of several data types to an ostringstream object:
double: 123.457
int: 22
address of int: 0012FE94
more characters added

 2003 Prentice Hall, Inc.


All rights reserved.
49

15.12 String Stream Processing

• String input
– istringstream inputString ( myString );
– inputString >> string1 >> string2
– Like reading from cin

 2003 Prentice Hall, Inc. All rights reserved.


50
1 // Fig. 15.12: fig15_12.cpp
2 // Demonstrating input from an istringstream object.
Outline
3 #include <iostream>
4
fig15_12.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <string>
9
10 using std::string;
11
12 #include <sstream>
13
14 using std::istringstream;
15
Create and initialize
16 int main()
17 {
istringstream object.
18 string input( "Input test 123 4.7 A" );
19 istringstream inputString( input );
20 string string1;
21 string string2;
22 int integer;
23 double double1;
24 char character;
25

 2003 Prentice Hall, Inc.


All rights reserved.
51
26 inputString >> string1 >> string2 >> integer >> double1
27 >> character;
Outline
28
29 cout << "The following items were extracted\n"
fig15_12.cpp
30 << "from the istringstream object:"
(2 of 2)
31 << "\nstring: " << string1
Read data into variables.
32 << "\nstring: " << string2
33 << "\n int: " << integer
34 << "\ndouble: " << double1
35 << "\n char: " << character;
36
37 // attempt to read from empty stream
38 long value;
39
good returns 1 if can still
40 inputString >> value;
41
read data (no EOF, bad bits,
42 // test stream results etc). In this case, there is no
43 if ( inputString.good() ) data, so the test fails.
44 cout << "\n\nlong value is: " << value << endl;
45 else
46 cout << "\n\ninputString is empty" << endl;
47
48 return 0;
49
50 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
52
The following items were extracted
from the istringstream object:
Outline
string: Input
string: test
fig15_12.cpp
int: 123
output (1 of 1)
double: 4.7
char: A
 
inputString is empty

 2003 Prentice Hall, Inc.


All rights reserved.

You might also like