字符串模板
string 的创建、拼接、查找、截取——C++ 字符串操作大全
string
字符串
拼接
查找
截取
GESP3
#include <bits/stdc++.h>
using namespace std;
int main() {
// 创建
string s1 = "Hello";
string s2(5, 'a'); // "aaaaa"
// 输入
string s;
cin >> s; // 读一个词(遇空格停)
cin.ignore();
getline(cin, s); // 读整行
// 常用操作
cout << s.length() << endl; // 长度
cout << s.empty() << endl; // 是否为空
// 拼接
string t = s1 + " " + "World";
// 遍历
for (int i = 0; i < s.length(); i++)
cout << s[i];
for (char c : s)
cout << c;
// 截取 substr(起始, 长度)
string sub = t.substr(0, 5); // "Hello"
// 查找 find
int pos = t.find("World");
if (pos != string::npos)
cout << "找到,位置 " << pos << endl;
// 替换
t.replace(0, 5, "Hi"); // "Hi World"
// 插入与删除
t.insert(2, "!!"); // 在位置2插入
t.erase(2, 2); // 从位置2删2个
// 数字与字符串互转
int n = stoi("123"); // 字符串→整数
double d = stod("3.14"); // 字符串→浮点
string ns = to_string(42); // 整数→字符串
return 0;
}
📖 要点说明
cin >> s遇空格停止,getline读整行substr(pos, len)从 pos 开始取 len 个字符find找不到返回string::nposstoi/stod/to_string是 C++11 字符串数值转换
⚠️ 常见错误
cin >>和getline混用忘cin.ignore()substr第二个参数是长度不是结束位置find不检查npos就使用结果