C++/String/string replace
Содержание
Demonstrate insert(), erase(), and replace().
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1("A");
string str2("B");
cout << "Initial strings:\n";
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << "\n\n";
str1.insert(6, str2);
cout << str1 << "\n\n";
str1.erase(6, 9);
cout << str1 <<"\n\n";
str1.replace(7, 8, str2);
cout << str1 << endl;
return 0;
}
Replace all spaces with period
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
int main()
{
string string1( "abc edfgh ijk lmno pqr stu vw xyz" );
cout << "Original string:\n" << string1 << endl << endl;
int position = string1.find( " " ); // find first space
//
while ( position != string::npos )
{
string1.replace( position, 1, "." );
position = string1.find( " ", position + 1 );
}
cout << string1 << "\n\nAfter second replacement:\n";
return 0;
}
/*
Original string:
abc edfgh ijk lmno pqr stu vw xyz
abc.edfgh.ijk.lmno.pqr.stu.vw.xyz
After second replacement:
*/
string.replace()
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1("String handling C++ style.");
string str2("STL Power");
cout << "Initial strings:\n";
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << "\n\n";
// demonstrate replace
cout << "Replace 8 characters in str1 with str2:\n";
str1.replace(7, 8, str2);
cout << str1 << endl;
return 0;
}
/*
Initial strings:
str1: String handling C++ style.
str2: STL Power
Replace 8 characters in str1 with str2:
String STL Power C++ style.
*/
string.replace( position, 2, ";123", 5, 2 )
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
int main()
{
string string1( "abc edfgh ijk lmno pqr stu vw xyz" );
cout << "Original string:\n" << string1 << endl << endl;
int position = string1.find( "." ); // find first period
while ( position != string::npos )
{
string1.replace( position, 2, "12345;;123", 5, 2 );
position = string1.find( ".", position + 1 );
}
cout << string1 << endl;
return 0;
}
/*
Original string:
abc edfgh ijk lmno pqr stu vw xyz
abc edfgh ijk lmno pqr stu vw xyz
*/