1. 字符串的创建与初始化
std::string s1; // 空字符串
std::string s2 = "Hello"; // 用C风格字符串初始化
std::string s3("World"); // 用C风格字符串初始化
std::string s4 = s2 + " " + s3; // 字符串连接
std::string s5(5, 'a'); // 初始化为 "aaaaa"
2. 字符串的访问与修改
std::string s = "Hello";
// 访问字符
char c = s[0]; // 访问第一个字符,不进行边界检查
char d = s.at(1); // 访问第二个字符,进行边界检查(越界时抛出异常)
// 修改字符
s[0] = 'J'; // s 变为 "Jello"
s.append(" World"); // 追加字符串,s 变为 "Jello World"
s += "!"; // 追加字符,s 变为 "Jello World!"
// 插入与删除
s.insert(5, ","); // 在位置5插入逗号,s 变为 "Jello, World!"
s.erase(5, 2); // 从位置5开始删除2个字符,s 恢复为 "Jello World!"
3. 字符串的查找与替换
std::string s = "Hello World";
// 查找
size_t pos = s.find("World"); // 查找子串,返回位置(7)
if (pos != std::string::npos) { // 判断是否找到
// 处理找到的情况
}
// 替换
s.replace(6, 5, "Universe"); // 从位置6开始的5个字符替换为"Universe"
4.子串操作substr
std::string s="abcdefj"; // 0123456
cout<<s.substr(3)<<endl; // 从位置 3 开始提取到末尾 → "defj"
cout<<s.substr(s.size())<<endl; // 空
cout<<s.substr(s.size()-1)<<endl; // j
cout<<s.substr(2,4)<<endl; // 从位置 2 开始提取 4 个字符 → "cdef"
5.字符串与数值的转换
std::string numStr = std::to_string(42); // 整数转字符串
std::string floatStr = std::to_string(3.14); // 浮点数转字符串
int num = std::stoi("42"); // 字符串转整数
double d = std::stod("3.14"); // 字符串转双精度浮点数