目录
如后续需文字描述,,请评论区告诉我,我看到后会进行添加一些文字描述。
前言:
因本人女朋友在学习c++过程中在一些知识网页上学了string但是无法实现,发现别人上传的string函数用法有些错误,特写此文章以防误人子弟,主要介绍了string常见用法,其中包括:字符串截取,字符串区间删除,字符串排序与相加和查找,字符串插入与替换,因为比较基础特此便少些文字描述~(就是偷懒!~,但是绝对保证语法正确)
字符串截取
#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
string s,a1;
int main(){
s="0123456789";
a1=s.substr(5,2);
cout<<"字符串s"<<s<<endl;
cout<<"获得s在第5个位置长度为2的字符串:"<<a1<<endl;
return 0;
}
字符串插入与替换
#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
string s,a1;
int main(){
s="0123456789";
s.insert(s.begin()+5,'s');
cout<<s;
return 0;
}
#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
string s,a1;
int main(){
s="0123456789";
s.replace(5,0,"aaa");
cout<<"s在第5个位置添加“aaa”这个字符串:"<<s<<endl;
string s1="0123456789";
s1.replace(5,2,"aaa");
cout<<"s1在第5个位置到第7个位置换成“aaa”这个字符串:"<<s1<<endl;
return 0;
}
字符串区间删除
#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
string s,a1;
int main(){
s="0123456789";
s.erase(5,2);
cout<<"字符串s:"<<s<<endl;
cout<<"删掉s在第5个位置长度为2的字符串“56”:"<<s<<endl;
return 0;
}
字符串排序与相加和查找
#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
string s,s1;
int main(){
s="01234";s1="56789";
string S;
S=s1+s;
cout<<"字符串相加"<<S<<endl;
sort(S.begin(),S.end());
cout<<"字符串排序"<<S<<endl;
int a56=S.find("56");
int a99=S.find("99");
cout<<"字符串查找,如果能查找到返回查找到的第一个字符下标:"<<a56<<endl;
cout<<"查找不到返回-1:"<<a99<<endl;
cout<<"查找既可以是字符也可以是字符串"<<endl;
return 0;
}