C++ replace()函数返回string 能放的最大元素个数。(不同于capacity)
size _ type max _ size( ) const; basic_string <char>::size_type cap, max; cap
= s.capacity ( ); max = s.max_size ( ); // max=4294967294.
basic_string::rfind 寻找给定的string。返回找到的第一个string 下标值;如果没找到
则返回npos。
与find 不同的是:rfind 默认从npos 开始找。其他相同。
basic_string::replace 将原string 中的元素或子串替换。返回替换后的string。
#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 << "nn";// 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 PowerReplace 8 characters in str1 with str2:
String STL Power C++ style.*/
指定具体位置#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 xyzabc edfgh ijk lmno pqr stu vw xyz
*/
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 << "nn";
str1.insert(6, str2);
cout << str1 << "nn";
str1.erase(6, 9);
cout << str1 <<"nn";
str1.replace(7, 8, str2);
cout << str1 << endl;
return 0;
}