摘要:本文主要向大家介绍了 C/C++知识点之C++中string的操作,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
本文主要向大家介绍了 C/C++知识点之C++中string的操作,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
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函数需要包含
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;
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C/C+频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号