字符串处理
子串 substr、查找 find、转换 stoi/to_string、字符判断
字符串处理
std::string 自带几十个方法,配合 <algorithm> 可以高效处理文本。
学完本章你将: 掌握 substr/find/replace、stoi/to_string、字符分类。
子串与查找
cpp
#include <iostream>
#include <string>
int main() {
std::string s = "Hello World";
// 子串
std::string sub = s.substr(0, 5); // "Hello"
std::string tail = s.substr(6); // "World"(6 到末尾)
// 查找
size_t pos = s.find("World"); // 6(首次出现位置)
if (pos != std::string::npos) { // npos 表示没找到
std::cout << "找到了,位置:" << pos << "\n";
}
// 替换
s.replace(0, 5, "Hi"); // "Hi World"
// 插入/删除
s.insert(0, "Oh, "); // "Oh, Hi World"
s.erase(0, 4); // "Hi World"
return 0;
}
字符串与数字转换
cpp
// 字符串 → 数字
int i = std::stoi("42");
double d = std::stod("3.14");
long l = std::stol("1234567890");
// 数字 → 字符串
std::string s = std::to_string(42); // "42"
std::string pi = std::to_string(3.14159); // "3.141590"
stringstream 分割
cpp
#include <sstream>
std::string input = "apple banana cherry";
std::istringstream iss(input);
std::string word;
while (iss >> word) {
std::cout << "[" << word << "]\n";
}
// [apple] [banana] [cherry]