string常用操作
string的定义及赋值
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
string s1="hellow world";
string s2={"hellow world"};
string s3(s1);
cout<<s1<<endl<<s2<<endl<<s3<<endl;
return 0;
}
string的长度
- size()返回字符串长度
- length()返回字符串长度(等价于size())
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
string s;
cin>>s;
cout<<"字符串长度为"<<s.size();
return 0;
}
判断字符串是否为空
- empty()判断字符串是否为空,若为空则返回1,否则返回0
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
string s1="hellow";
string s2="";
if(s1.empty()) cout<<"字符串s1为空"<<endl;
else cout<<"字符串s1长度为"<<s1.size()<<endl;
if(s2.empty()) cout<<"字符串s2为空"<<endl;
else cout<<"字符串s2长度为"<<s2.size()<<endl;
return 0;
}
清空字符串
- clear()清空字符串
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
string s="heoolw";
s.clear();
cout<<s<<endl;
return 0;
}
字符串的反转
- reverse()将字符串反转
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
string s="hellow";
reverse(s.begin(),s.end());
cout<<s;
return 0;
}
字符串的插入
- push_back()在字符串末尾插入一个字符
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
string s="heool";
s.push_back('w');
cout<<s;
return 0;
}
字符串的截取
-
格式1:s.substr(a,b);
- 1、s 需要截取的字符串
- 2、a 截取字符串的开始位置(注:当a等于0或1时,都是从第一位开始截取)
- 3、b 要截取的字符串的长度
-
格式2:s.substr(a) ;
- 1、s 需要截取的字符串
- 2、a 可以理解为从第a个字符开始截取后面所有的字符串。
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
string s="hellow";
string s1=s.substr(2,5);
string s2=s.substr(2);
cout<<s1<<endl;
cout<<s2<<endl;
return 0;
}