提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
在竞赛中,字符串是必考的考点,只是通过定义去处理字符串运算,相当麻烦,但如果用到STL的string库中的函数,可以简便的处理字符串运算,接下来列举比较常见的函数。
string s = "Hello";
char c1 = s[0]; // 访问第 0 个字符 'H'
char c2 = s.at(1); // 访问第 1 个字符 'e'(带边界检查)
string s = "Hello";
int len = s.size(); // 获取字符串长度(推荐)
int len2 = s.length(); // 获取字符串长度
bool isEmpty = s.empty(); // 判断字符串是否为空
string s1 = "Hello";
string s2 = "World";
string s3 = s1 + " " + s2; // 拼接字符串
s1.append(" World"); // 追加字符串
s1 += "!"; // 追加字符
string s = "Hello World";
string sub = s.substr(6, 5); // 从第 6 个字符开始,提取 5 个字符("World")
string s = "Hello World";
size_t pos1 = s.find("World"); // 查找子字符串 "World" 的位置
size_t pos2 = s.find('o'); // 查找字符 'o' 的位置
size_t pos3 = s.find("abc"); // 查找不存在的子字符串,返回 string::npos
if (pos3 == string::npos) {
cout << "Not found" << endl;
}
string s = "Hello World";
s.replace(6, 5, "C++"); // 从第 6 个字符开始,替换 5 个字符为 "C++"
string s = "Hello World";
s.insert(5, " C++"); // 在第 5 个字符后插入 " C++"
string s = "Hello World";
s.erase(5, 6); // 从第 5 个字符开始,删除 6 个字符
string s1 = "Hello";
string s2 = "World";
if (s1 == s2) {
cout << "Equal" << endl;
} else if (s1 < s2) {
cout << "s1 is smaller" << endl;
} else {
cout << "s1 is larger" << endl;
}
string s = "123";
int num = stoi(s); // 字符串转整数
double d = stod("3.14"); // 字符串转浮点数
string s2 = to_string(42); // 整数转字符串
string s = "Hello";
s.clear(); // 清空字符串
string s1 = “Hello”;
string s2 = “World”;
s1.swap(s2); // 交换 s1 和 s2 的内容
#include
string s = "Hello";
transform(s.begin(), s.end(), s.begin(), ::toupper); // 转换为大写
transform(s.begin(), s.end(), s.begin(), ::tolower); // 转换为小写
string s = " Hello World ";
s.erase(0, s.find_first_not_of(' ')); // 去除开头空格
s.erase(s.find_last_not_of(' ') + 1); // 去除结尾空格
string s = "Hello World";
if (s.starts_with("Hello")) { // C++20 特性
cout << "Starts with Hello" << endl;
}
if (s.ends_with("World")) { // C++20 特性
cout << "Ends with World" << endl;
}