//字符串内容修改和替换
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1("123456");
string str2("abcdefghijklmn");
string str;
//使用str1初始化str
str.assign(str1);
cout<<str<<endl;
//使用str1的第3位长度为3子串初始化str
str.assign(str1,3,3);
cout<<str<<endl;
//使用str1的第二位开始到字符串结束初始化str
str.assign(str1,2,str1.npos);
cout<<str<<endl;
//使用五个‘A’初始化str
str.assign(5,'A');
cout<<str<<endl;
string::iterator itB;
string::iterator itE;
//获取字符串起始位置
itB=str1.begin();
//获取字符串末端位置指针
itE=str1.end();
str.assign(itB,(--itE));
cout<<str<<endl;
str=str1;
cout<<str<<endl;
//删除元素 3号位及其之后
str.erase(3);
cout<<str<<endl;
str.erase(str.begin(),str.end());
cout<<":"<<str<<":"<<endl;
//交换元素
str.swap(str2);
cout<<str<<endl;
//插入元素
string A("ello World");
string B("H");
B.insert(1,A);
cout<<B<<endl;
//插入元素
A="ello";
B="H";
B.insert(1,"yanchy",3);
cout<<"插入:"<<B<<endl;
//插入元素
A="ello";
B="H";
B.insert(1,A,2,2);
cout<<"插入:"<<B<<endl;
//插入元素
A="ello";
B="H";
B.insert(1,5,'C');
cout<<"插入:"<<B<<endl;
//插入内容
A="ello";
B="H";
string::iterator it=B.begin()+1;
const string::iterator itF=A.begin();
const string::iterator itG=A.end();
B.insert(it,itF,itG);
cout<<"插入:"<<B<<endl;
A="ello";
B="H";
cout<<"A= "<<A<<",B= "<<B<<endl;
//追加字符串
B.append(A);
cout<<"追加:"<<B<<endl;
A="ello";
B="H";
cout<<"A= "<<A<<",B= "<<B<<endl;
B.append("12345",2);
cout<<"追加:"<<B<<endl;
A="ello";
B="H";
cout<<"A= "<<A<<",B= "<<B<<endl;
B.append("12345",2,3);
cout<<"追加:"<<B<<endl;
A="ello";
B="H";
cout<<"A= "<<A<<",B= "<<B<<endl;
B.append(10,'a');
cout<<"追加:"<<B<<endl;
A="ello";
B="H";
cout<<"A= "<<A<<",B= "<<B<<endl;
B.append(A.begin(),A.end());
cout<<"追加:"<<B<<endl;
cin.get();
return 0;
}
C++ STL string字符串内容修改和替换
最新推荐文章于 2024-07-25 09:44:13 发布