#include<bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
cout << s << endl;
cout << s.size() << endl;//4
cout << s[0] << endl;//'e'
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
string s;
getchar();
getline(cin,s);
cout << n << endl;
cout << s << endl;
return 0;
}
查找find函数
#include<bits/stdc++.h>
using namespace std;
int main() {
string s="hello world";
if(s.find("llo") != string::npos){
cout << "Yes";
cout << s.find("llo")<<endl;;// 找到的下标
}else{
cout << "No";
}
int k = s.find("lolo");
cout << k << endl;//k:-1;
if(k!=-1){
cout << k << endl;
}
s="hello world";
k = s.find("llo",3);//从下标3开始找"llo"
s="abcabababc";
k = s.rfind("ab");//k:7,从右边找到左边
return 0;
}
插入insert
#include<bits/stdc++.h>
using namespace std;
int main() {
string s="hello world";
s.insert(3,"abc");//在下标3前面插入"abc"
cout << s << endl;
s="hello world";
s = s+"abc";
cout << s << endl; //hello worldabc
s = "abc"+"efg";//错误: 两个字符串常量不能相加
return 0;
}
删除erase
#include<bits/stdc++.h>
using namespace std;
int main() {
string s="hello world";
s.erase(2,3);//从下标2开始删除3个字符
cout << s << endl; // he world
return 0;
}
更换更改replace
#include<bits/stdc++.h>
using namespace std;
int main() {
string s=;
s.replace(1,4,"i") ;//从下标1开始的后面4个字符修改成"i"
cout << s << endl;//"hi world"
return 0;
}
截取substr
#include<bits/stdc++.h>
using namespace std;
int main() {
string s="hello world";
string ts;
ts = s.substr(2,6);//从下标2开始截取6字符(llo wo)
cout << s << endl; // hello world
cout << ts << endl;// llo wo
return 0;
}