C++ String 基础语法完全指南

以下是对C++中string类语法知识的系统总结,包含基础操作、常用成员函数和进阶技巧,特别适合新手快速掌握核心知识点:

后续会不断补充,尽可能达到全部语法知识,以供后续查阅。


一、基础用法

#include <string>   // 必须包含的头文件
using namespace std; // string位于std命名空间

1. 声明与初始化

string s1;               // 空字符串
string s2 = "hello";     // 直接赋值
string s3(5, 'a');       // 生成5个'a' → "aaaaa" 
string s4(s2, 1, 3);     // 从索引1截取3字符 → "ell"
string s5(s2.begin(), s2.begin()+3); // 迭代器构造 → "hel"

2. 基本操作

s1 = s2 + " world";      // 拼接 → "hello world"
s1 += "!";               // 追加 → "hello world!"
bool eq = (s2 == "hello"); // 比较(区分大小写)
char c = s2[0];          // 访问字符 → 'h'(不会检查越界)
char c_safe = s2.at(0);  // 会抛出out_of_range异常

二、核心成员函数

1. 容量查询

int len = s2.size();     // 或 length() → 5
bool isEmpty = s2.empty(); // 判空(优于 size()==0)
s2.resize(10, 'x');      // 扩容到10字符,新空间填'x' → "helloxxxxx"

2. 字符串操作

size_t pos = s2.find("ll");  // 返回首次出现位置 → 2
pos = s2.find('o', 3);       // 从索引3开始找 → 4

// 子串
string sub = s2.substr(1, 3); // 从1开始取3字符 → "ell"

// 修改
s2.replace(2, 2, "LL");     // 替换索引2的2字符 → "heLLo"
s2.insert(5, " world");     // 在索引5插入 → "hello world"
s2.erase(5, 6);            // 删除从5开始的6字符 → "hello"

// 翻转 位于<algorithm>
reverse(s2.begin(), s2.end())	// => olleh 翻转的范围是 [first, last)

3. 遍历操作

string str = "Hello";
for(int i=0; i<str.size(); ++i) {  // 传统下标遍历
    cout << str[i] << " ";        // 输出:H e l l o 
}
for(auto it = str.begin(); it != str.end(); ++it) { // 迭代器遍历(STL风格)
    *it = toupper(*it);  // 修改字符为大写
    cout << *it << " ";  // 输出:H E L L O
}
for(char& c : str) {    // C++11范围for循环(推荐)引用方式可修改原字符串
    c = tolower(c);     // 转为小写
    cout << c << " ";   // 输出:h e l l o
}
const char* ptr = str.c_str();
while(*ptr != '\0') {       // C风格指针遍历 c_str()方法将C++ string转换为C风格字符串
    cout << *ptr++ << " ";  // 输出:h e l l o
}
#include <algorithm>
for_each(str.begin(), str.end(), [](char& c) {  // STL算法遍历
    c = c + 1;           // 每个字符ASCII值+1
    cout << c << " ";    // 输出:i f m m p
});

三、进阶技巧

1. 输入输出

string input;
cin >> input;            // 读取到空白符停止
getline(cin, input);     // 读取整行(包含空格)

2. 性能优化

s1.reserve(100);         // 预分配内存(减少多次扩容开销)
s1.shrink_to_fit();      // 释放多余内存(C++11+)

3. 特殊用法

// C风格转换(注意生命周期)
const char* cstr = s2.c_str(); 

// 原始字符串(C++11+)
string path = R"(C:\Program Files\test)";  // 原始字符串以R"(开头,以)"结束。括号内的内容不会被转义

// 数值转换
string numStr = to_string(3.14);  // double转string
int val = stoi("42");            // string转int