string
string其实很像vector
string s的输出可以直接cout << s;
s.append(n,字符)或s.append(字符串):在s字符串末尾添加n个字符或一个字符串
#include<bits/stdc++.h>
using namespace std;
int main(){
string s(10,'#');
cout << s << endl;
s.append(3,'*');
s.append("+++");
cout << s;
return 0;
}
s.substr(a):截取第a个元素后所有元素
s.substr(a,b):截取第a个元素后的b个元素
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
s.append("abcdefghijklmn");
cout << s << endl;
//截取第四个元素后的所有字符
cout << s.substr(4) << endl;
//截取第七个字符后的3个字符
cout << s.substr(7,3) << endl;
return 0;
}
高版本的c++支持如下这种遍历字符串方式(我的C++98不支持)
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
s.append("abcdefghijklmn");
for(char c : s){
cout << c << endl;
}
return 0;
}
输入字符串的三种方法
- scanf("%s",s.data()):用的不多
- cin >> s:有空格就不行了
- getline(cin,s):能读一整行,用的最多
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
//cin读整个句子
cin >> s;
cout << s << endl;
return 0;
}
可以发现只读进去了this,碰到空格就会出问题
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
//getline读一整行
getline(cin,s);
cout << s << endl;
return 0;
}
string的查找
s.find():返回字串在母串中的位置,如果母串中没有子串,则返回s.npos(是一个很大的整型数字)
#include<bits/stdc++.h>
using namespace std;
int main(){
string s("abcdabcd");
cout << " s.npos:" << s.npos << endl;
cout << " 没找到:" << s.find("jk") << endl;
cout << " 从头开始子串出现的位置::" << s.find("cd") << endl;
cout << " 找4号位置后子串出现的位置:" << s.find("cd",4);
return 0;
}
s.find_first_of(子串):返回子串在母串中第一次出现的位置
s.find_last_of(子串):返回子串在母串中最后一次出现的位置
#include<bits/stdc++.h>
using namespace std;
int main(){
string s("abcdabcd");
cout << " 子串首次出现位置:" << s.find_first_of("ab") << endl;
cout << " 子串最后一次出现位置:" << s.find_last_of("ab") << endl;
return 0;
}
s.rfind():从后往前反向查找,一般用正向查找和反向查找得到子串的位置不同来证明子串不唯一