目录
1.string是什么
2.string的构造
代码示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1;
const char* str = "hello!";
string s2(str);
cout << s2 << endl;
string s3(s2);
cout << s3 << endl;
string s4(5,'a');
cout << s4;
return 0;
}
3.string的赋值操作
代码示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1;
s1 = "hello!";
cout << s1 << endl;
string s2;
s2 = s1;
cout << s2 << endl;
string s3;
s3 = 'a';
cout << s3 << endl;
string s4;
s4.assign("hello!!!!!");
cout << s4 << endl;
string s5;
s5.assign("mygo!!!!!",5);
cout << s5 << endl;
string s6;
s6.assign(s5);
cout << s6 << endl;
string s7;
s7.assign(5,'a');
cout << s7 << endl;
return 0;
}
4.string字符串拼接
代码示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1 = "my";
s1 += "go!!!!";
cout << s1 << endl;
s1 += '!';
cout << s1 << endl;
string s2 = " ave";
s1 += s2;
cout << s1 << endl;
s1.append(" mujica");
cout << s1 << endl;
s2.append("mujica",3);
cout << s2 << endl;
s2.append(s1);
cout << s2 << endl;
string s3 = "hello";
s3.append(s1,2,7);
cout << s3 << endl;
return 0;
}
5.string查找和替换
代码示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s = "starrail";
//查找
int pos1 = s.find("r");
cout << pos1 << endl;
int pos2 = s.find("zenlesszonezero");
cout << pos2 << endl;
//不存在会输出-1
int pos4 = s.rfind("r");
//rfind从右往左查,但也是从左往右计算下标位置
cout << pos4 << endl;
//替换
//下标4开始替换3个字符
//或者说删掉下标4开始的3个字符,并且将github放在那个空位,其它的不变
s.replace(4,3,"github");
cout << s << endl;
return 0;
}
6.字符串比较
代码示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1 = "starrail";
string s2 = "black myth";
//按照ascii码一个字母一个字母的比较
//s在b的后面,更大
cout << s1.compare(s2);
return 0;
}
7.string字符存取
代码示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1 = "starrail";
for(int i = 0; i < s1.size(); i++)
{
cout << s1[i] << ' ';
}
cout << endl;
for(int i = 0; i < s1.size(); i++)
{
cout << s1.at(i) << ' ';
}
return 0;
}
8.string插入和删除
代码示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1 = "starrail";
//插入
//在2下标的元素的左边插入
s1.insert(2," hello ");
cout << s1 << endl;
s1.erase(2,7);
//从第2个位置起删7个
cout << s1 << endl;
return 0;
}
8.string字串获取
代码示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1 = "starrail";
string s2 = s1.substr(1,6);
cout << s2 << endl;
return 0;
}