1. 定义一个字符串
头文件 #include <string>
初始化 string s1; string s2=s1; string s3='abc'; string s4=words[i];
2. 读写字符串操作
cin >> s1; // 单字符串输入,读入字符串,遇到空格或回车停止
cin >> s2 >> s3; // 多字符串的输入,遇到空格转到下个字符串赋值,回车停止
getline(cin , s1); //读入字符串中保留空格
count << s1 << endl;
3. 查询字符串、索引
string s1 = "abc"; // 初始化一个字符串
cout << s1.empty() << endl; // s 为空返回 true,否则返回 false
cout << s1.size() << endl; // 返回 s1 中字符个数,不包含空字符
cout << s1.length() << endl; //返回 s1 中字符个数,不包含空字符
cout << s1[1] << endl; // 字符串本质是字符数组
4. 拼接、比较等操作
s1+s2 //返回s1和s2拼接后的结果
s1==s2 //如果s1和s2中的元素完全相等则它们相等,区分大小写
s1!=s2
<, <=, >, >= //利用字符的字典序进行比较,区分大小写
5. cctype头文件(判断字符类型:大/小写字母、标点、数字等)
#include <cctype>
isalnum(c) //当是字母或数字时为真
isalpha(c) //当是字母时为真
isdigit(c) //当是数字是为真
islower(c) //当是小写字母时为真
isupper(c) //当是大写字母时为真
isxdigit(c) //当是16进制数字是为真
tolower(c) //若c是大写字母,转换为小写输出,否则原样输出
toupper(c) //若c是小写字母,转换为大写输出,否则原样输出
7. 修改string的操作
s.insert(pos, args) //在pos之前插入args指定的字符
s.insert(0, s2) //在s的位置0之前插入s2的拷贝
s.append(args) //将args追加到s,args不能是单引号字符,若是单个字符则必须用双引号表示
s.replace(range, args) //将s中范围为range内的字符替换为args指定的字符,range或者是一个下标或长度,或者是一对指向s的迭代器
s.replace(3, 6, "aaa") //从位置3开始,删除6个字符,并插入"aaa",删除插入的字符数量不必相等
8. string搜索操作
s.find(args) //查找s中args第一次出现的位置
s.rfind(args) //查找s中args最后一次出现的位置
s.find_first_of(args) //在s中查找args中任何一个字符最早出现的位置
s.find_last_of(args) //在s中查找args中任何一个字符最晚出现的位置
例如:
string s1="nice to meet you~";
cout << s1.find_first_of("mey") << endl; // 输出结果为 3,'e' 出现的最早
s.find_first_not_of(args) //查找s中第一个不在args中的字符的位置
s.find_last_not_of(args) //查找s中最后一个不在args中的字符的位置
例如:
string s1 = "nice to meet you~";
cout << s1.find_first_not_of("nop") << endl; //输出结果为1,'i'不在"nop"里
9. string、char型与数值的转换
string s = to_string(val) //将数值val转换为string,val可以是任何算术类型(int、浮点型等)
string s1 = "11"; //初始化一个空字符串
int a1 = stoi(s1); //将字符串当作十进制转换
cout << a1 << endl; //输出11
int a2 = stoi(s1, nullptr, 8); //将字符串当作八进制转换
cout << a2 << endl; //输出9
int a3 = stoi(s1, nullptr, 2); //将字符串当作二进制转换
cout << a3 << endl; //输出3
10. 字符串反转
#include <algorithm>
string s2 = "12345"; //初始化一个字符串
reverse(s2.begin(), s2.end()); //反转string定义的字符串s2
cout << s2 << endl; //输出54321
11. 提取字串
string ss = s.substr(pos, n) //从索引pos开始,提取连续的n个字符,包括pos位置的字符