1
// Demonstrating string
member functions erase and replace.
2
#include <iostream>
3
using std::cout;
4
using std::endl;
5
6
#include <string>
7
using std::string;
8
9
int main()
10
{
11
// compiler concatenates all parts into one
string
12
string string1( "The values in any left
subtree"
13
"\nare less than the value in
the"
14
"\nparent node and the values
in"
15
"\nany right subtree are greater"
16
"\nthan the value in the parent
node" );
17
18
cout << "Original string:\n"
<< string1 << endl << endl;
19
20
// remove all characters from (and
including) location 62
21
// through the end of string1
22
string1.erase( 62 );
23
24
// output new string
25
cout << "Original string after
erase:\n" << string1
26
<< "\n\nAfter first
replacement:\n";
27
28
int position = string1.find( " "
); // find first space
29
30
// replace all spaces with period
31
while ( position != string::npos )
32
{
33
string1.replace( position, 1,
"." );
34
position = string1.find( " ",
position + 1 );
35
} // end while
36
37
cout << string1 <<
"\n\nAfter second replacement:\n";
38
39
position = string1.find( "." ); //
find first period
40
41
// replace all periods with two semicolons
42
// NOTE: this will overwrite characters
43
while ( position != string::npos )
44
{
45
string1.replace( position, 2,
"xxxxx;;yyy", 5, 2 );
46
position = string1.find( ".",
position + 1 );
47
} // end while
48
49
cout << string1 << endl;
50
return 0;
51
} // end main
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
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
|