1.截取substr(index,size),从下标index处截取长为size的内容,深拷贝。
int main() {
string s = "hello world";
string s2 = s.substr(6, 5);//截取world
cout << s << endl;//输出hello world
cout << s2 << endl;//输出world
}
2.末尾添加字符push_back
int main() {
string s = "hello world";
string s2 = s.substr(6, 5);//截取world
s2.push_back('h');//尾部添加字符h,s2=worldh
cout << s2;//输出worlds
}
3.字符串拼接,直接使用+运算
int main() {
string s = "hello world";
cout << s+" HL" <<endl;//输出hello world HL
}
4.字符串长度size(),不包含最后的‘\0’字符。
int main() {
string s = "hello world";
cout << s.size() << endl;//输出11
}
5.字符串分割,使用stringstream API,需要添加sstream类
int main() {
string s = "hello world HL";//原始字符串
stringstream ss(s);//创建字符串流
while (getline(ss, s, ' '))//依次获得按空格分开的每个字符串,并存储在s中
{
cout << s << endl;//依次输出hello、world、HL三个字符串
}
}
6.查找子字符串find(),返回第一次出现的位置,没有会返回一个无穷大值。
int main() {
string s = "hello world";
string s2 = s.substr(6, 5);//截取s中下标为6长度为5的字符串world
cout << s.find(s2) << endl;//输出6,world在s中第一次出现位置下标是6
if (s.find(s + "z")>s.size())//找不到会返回一个无穷大值
{
cout << "no find";
}
}
7.数字转字符串to_string,字符串转数字stoi(string to int)。记得添加sstream类。python中可以直接使用加法运算。
int main() {
string s = "hello world";
cout << s + to_string(512)<<endl;//输出hello world512
cout << 10+stoi("510") << endl;//输出520
}
其他(相对使用没那么多)
8.判断是否是数字或字符isalnum(is alphabet or num)
#include<iostream>
using namespace std;
int main()
{
//字母数字则返回非零值,其他返回0
cout << isalnum('4') << endl;
cout << isalnum('a') << endl;
cout << isalnum(',') << endl;
}
9.大小写字符转换tolower/toupper,只处理大小写字符,其他不处理,返回的是ascii码值,可以自行强制转换。
#include<iostream>
using namespace std;
int main()
{
cout << tolower('A') << endl;//输出‘a’的ascii码值97
cout << tolower('1') << endl;//输出‘1’的ascii码值49
cout << (char)toupper('a') << endl;//强转为字符输出‘A’
cout << toupper('.') << endl;//输出‘.’的ascii码值46
}