标签:需要 cat 翻译 ase c_str ret hello aabb you
1、字符串的初始化以及读取
int main()
{
string s1="aaa";
string s2="bbb";
string s3=s1; //考虑构造函数
string s4(10,‘a‘); //初始化为“aaaaaaaaaa"
cout<<s1<<endl;
cout<<s2<<endl;
cout<<s3<<endl;
cout<<s4<<endl;
cout<<"迭代器方法"<<endl;
for( string::iterator it = s1.begin(); it != s1.end(); it++ ){
cout<< *it <<" ";
}
cout<<"\nat方法取元素"<<endl;
//使用at取元素
for(int i=0; i<s1.length();i++){
cout<<s1.at(i)<<" "; //使用at可以抛出异常
}
return 0;
}
2、 获取字符串的首地址、复制、连接操作
int main(){
string s="abcd";
printf("%s\n",s.c_str()); //获取字符串的首地址
//将s中的内容copy到buf中
char buf[128]={0}; //初始化空值
s.copy(buf,3,0);
cout<<"buf: "<<buf<<endl;
//连接字符串
string s1="aaa";
string s2="bbb";
string ss=s1+s2;
string s3="1111";
string s4="2222";
s3.append(s4);
cout<<"ss: "<<ss<<endl;
cout<<"s3: "<<s3<<endl;
return 0;
}
3、字符串的查找与替换操作
int main(){
//字符串的查找与替换
string s="hello, just enjoy the world,hello, just enjoy the world.hello, just enjoy the world.";
int index=s.find("hello",0); //从0的位置开始查找
cout<<"index : "<<index<<endl;
//求hello出现的次数
int cindex=s.find("hello",0);
while (cindex != string::npos) {
cout<< "cindex: "<<cindex<<endl;
s.replace(cindex,5,"HELLO"); //替换操作 从cindex号位置开始,将其中5哥字符换成”HELLO"
cindex=s.find("hello",cindex+1);
}
cout<<s<<endl;
return 0;
}
4、字符串的删除操作
int main(){
string s="hello, world,I hello am hello walking on hello the way";
string::iterator it = find(s.begin(),s.end(),‘l‘);
if (it != s.end()) {
s.erase(it);
}
cout<<"s删除后的结果是: "<<s<<endl;
//指定连续位置删除
s.erase(s.begin()+7,s.begin()+15);
cout<<"第二次删除: "<<s<<endl;
string s2="afghi";
s2.insert(1,"bcde");
cout<<"s2: "<<s2<<endl;
return 0;
}
5、transform在string中的应用
std::transform在指定的范围内应用于给定的操作,并将结果存储在指定的另一个范围内。要使用std::transform函数需要包含<algorithm>头文件。
int main(){
string s1="AAAAbbbbccccDDDD";
/* transform(b1,e1,b2,op) //把一个区间[b1,e1)内的数据经过(op)转化,放入第二个容器内
* 加上::的原因
* The problem is that the version of std::tolower inherited from the C standard library is a non-template function,
* but there are other versions of std::tolower that are function templates,
* and it is possible for them to be included depending on the standard library implementation.
* You actually want to use the non-template function,
* but there is ambiguity when just tolower is provided as the predicate.
* 翻译过来就是说,既有C版本的toupper/tolower函数,又有STL模板函数toupper/tolower,二者存在冲突。
*/
transform(s1.begin(),s1.end(),s1.begin(),::toupper);
cout<<s1<<endl;
return 0;
}
标签:需要 cat 翻译 ase c_str ret hello aabb you
原文地址:https://www.cnblogs.com/helloworldcode/p/9507921.html