C++におけるStringの各種動作
12096 ワード
1.stringの各種動的、静的付与
2.stingの遍歴
3.文字ポインタとstringを交換する
4.文字列の部分コピー
5.文字列の接続
6.文字列の検索と置換
7、大文字と小文字の変換
8.区間の挿入と削除
完全なコード:
//
string s1=("abckd");
string s2("bbbbb");
string s3(s1);
string s4=s2;
//
string s5;
cin>>s5;
2.stingの遍歴
string s="xiaojaiyu";
string::iterator iter;
//
for(int i=0;i<=s.length()-1;i++){
cout<//
for(iter=s.begin();iter!=s.end();iter++){
cout<
3.文字ポインタとstringを交換する
string s;
cin>>s;
char buf[128];
strcpy(buf,s.c_str());
//
cout<<"buf:"<
4.文字列の部分コピー
string s="xiao jia yu";
char a[20];
s.copy(a,3,3);// 3
5.文字列の接続
//
string s1="xiao";
string s2="jiayu"
string s3=s1+s2;
//
string s4="bang";
s4.append(s3);
6.文字列の検索と置換
string s1="wbm hello wbm 111 wbm 222 wbm 333";
// wbm
int offindex=s1.find("wbm",0);// 0
// string wbm
int offindex=s1.find("wbm",0);// -1
while(offindex!=s1.npos){
cout<<"offindex:"<"wbm",offindex);
}
// wbm
int offindex=s1.find("wbm",0);
while(offindex!=s1.npos){
s1.replace(offindex,3,"WBM");
offindex++;
offindex=s1.find("wbm",offindex);
}
7、大文字と小文字の変換
string s1='AAAbbb';
transform(s1.begin(),s1.end(),s1.begin(),toupper);//
transform(s1.begin(),s1.end(),s1.begin(),tolower);
8.区間の挿入と削除
string s1="hello1 hello2 hello3"
int index=s1.find('l',0);
while(index!=s1.npos){
s1.erase(index,1);
//index++; ,
index=s1.find("l",index);
}
//
s1.erase(s1.begin(),s1.end());
完全なコード:
#include
#include
#include
#include
using namespace std;
//string
void f1(){
string s1="shihao";//
string s2("bbbbbb");
string s3(s1);// coPy
string s4(10,'a');// string s4=("aaaaaaaaaa")
string s5;
cin>>s5;//
cout<cout<cout<cout<cout<//string
void f2(){
string s="fanyanfutianxiadiyi";
string::iterator iter;
//
for(int i=0;i1;i++){
cout<"";
}
cout<//
for(iter=s.begin();iter!=s.end();iter++){
cout<"";
}
cout<// string
void f4(){
string s1="aaabbb";
cout<//
char buf[128]={0};
s1.copy(buf,3,3);// ,
cout<<"buf:"<//
void f5(){
//1:
string s1="aaa";
string s2="bbb";
s1=s1+s2;
cout<<"s1:"<//2
string s3="fanyanfu";
s3.append(s1);
cout<<"s3:"<//
void f6(){
string s1="wbm hello wbm 111 wbm 222 wbm 333";
//
int index=s1.find("wbm",2);// 0
cout<<"index:"<// wem
int offindex=s1.find("wbm",0);
while(offindex!=s1.npos){
cout<<"offindex:"<"wbm",offindex);
}
// wbm
offindex=s1.find("wbm",0);
while(offindex!=s1.npos){
s1.replace(offindex,3,"WBM");
offindex++;
offindex=s1.find("wbm",offindex);
}
cout<<" :"<// aaa
string s2="aaa bbb ccc";
index=s2.find("aaa",0);
s2.replace(index,3,"AAA");
cout<"s2:"<//
void f7(){
string s1="AAAbbb";
transform(s1.begin(),s1.end(),s1.begin(),toupper);
cout<<" :"<tolower);
cout<<" :"<//
void f8(){
string s1="hello1 hello2 hello1";
int index=s1.find("l",0);
while (index!=s1.npos){
s1.erase(index,1);
index=s1.find("l",index);
}
cout<<" :"<cout<<" :"<int main(){
f4();
system("pause");
return 0;
}