string
创建
创建一个字符串或者字符串数组如下
用 cin 输入,可以读一整串字符直到空格或换行才结束
cpp
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
string strs[N];
cin >> s;
for (int i = 0; i < N; i ++ )
{
cin >> strs[i];
}
cout << s << endl;
for (int i = 0; i < N; i ++ )
{
cout << strs[i] << endl;
}
return 0;
}
访问大小
.size() 和 .length() 可以访问字符串的长度
cpp
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s.size() << endl;
return 0;
}
开头与结尾
.begin()是开头的地址
.end()是结尾的地址
插入
.push_back() 可以尾插
.insert() 可以精确插入,其中放插入的位置和插入的字符内容
cpp
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s << endl;
s.push_back('5');
cout << s << endl;
s.insert(s.begin(), '0');
cout << s << endl;
return 0;
}
删除
.erase(),里面放地址
cpp
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s << endl;
s.erase(s.begin());
cout << s << endl;
return 0;
}
查找
find(),里面放字符串或者字符,返回下标数字
cpp
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s << endl;
cout << s.find('1') << endl;
return 0;
}
下面是放字符的情况
cpp
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s << endl;
cout << s.find("23") << endl;
return 0;
}
截取
substr(), 放两个数,一个是下标,一个是截取的长度
cpp
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s << endl;
s = s.substr(2, 5);
cout << s << endl;
return 0;
}
比较
string会默认按字典序比较,由高位向低位去比较
cpp
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s1 = "123456", s2 = "12345";
cout << (s1 > s2) << endl;
s1 = "12345", s2 = "12346";
cout << (s1 > s2) << endl;
return 0;
}
拼接
cpp
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s1 = "123456", s2 = "789";
string s3 = s1 + s2;
cout << s3 << endl;
return 0;
}
反转
reverse(开始地址, 结束地址)可以反转内容