- string无须担心越界情况(当string串较小时,系统会分配更多空间给字符串)
- a=b//a字符串赋值给b字符串
- a+=b||a=a+b//b的字符串接到a的字符串的后面
- b+=a||b=b+a//b的字符串接到a的字符串的前面
- a==b;a!=b//比较字符串是否相等,返回布尔型
- a<=b;//基于字典序的比较,返回布尔值、
2.如果字符串需读入空格用cin的话,读到空格便以为结束了,比如以下代码:
#include<bits/stdc++.h>
using namespace std;
Int main(){
string a;
cin>>a;
cout<<a;
}
测试样例:
asdf ghjkl
应输出:
asdf ghjkl
但却输出了:
asdf
这时,我们便用getchar来代替cin,格式如下:
#include<bits/stdc++.h>
using namespace std;
Int main(){
string a;
getchar(cin,a);
cout<<a;
}
这时,便可以输出整句话了。
3.string类有一些常用的成员函数可进行字符串处理:
str.substr(pos,length1);
//返回对象的一个子串,从pos位置起,长length1个字符
str.empty( ); //查是否空串
str.insert(pos,str2); //将str2插入str的pos位置处
str.erase(pos,length1);
//在str位置pos处起,删除长度为length1的字串
str.find(str1); //返回str1首次在str中出现时的索引
str.find(str1,pos);
//返回从pos处起str1首次在str中出现时的索引
str.rfind(str1); //返回str1最后一次在str中出现时的索引
str.length(str); //返回串长度
判断是否找到子串的条件:if(str.find(str1)!=-1) 找到
if(str.rfind(str1)!=-1) 找到
- repace替换函数
A、用str1替换指定字符串从起始位置pos开始长度为len的字符