【C++必知必会】字符串操作速记

干了这么多年C++,每次处理字符串还得查文档,真是说不过去!今天我决定把这些常用的字符串操作函数背下来,整理成这份速记指南。

在C++中,字符串操作主要依赖于 <string> 头文件。掌握字符串处理是C++编程中的核心技能之一。


必须掌握的头文件

cpp 复制代码
#include <string>    // 主要头文件
#include <iostream>  // 用于输入输出
#include <sstream>   // 字符串流处理
#include <algorithm> // 用于字符串算法

必须掌握的字符串操作

1. 字符串创建和初始化

cpp 复制代码
string str1;                    // 空字符串
string str2 = "Hello";         // 直接初始化
string str3("World");          // 构造函数初始化
string str4(5, 'A');           // "AAAAA"
string str5 = str2 + " " + str3; // 字符串拼接

2. 获取字符串信息

cpp 复制代码
int len = str.length();        // 字符串长度
int size = str.size();         // 同length()
bool empty = str.empty();      // 是否为空

3. 访问字符串内容

cpp 复制代码
char first = str[0];           // 通过下标访问
char first_safe = str.at(0);   // 安全访问,会检查边界
char last = str.back();        // 最后一个字符
char first_char = str.front(); // 第一个字符

4. 字符串查找

cpp 复制代码
size_t pos = str.find("hello");    // 查找子串
size_t rpos = str.rfind("hello");  // 从后往前查找
size_t found = str.find_first_of("aeiou");  // 查找任意匹配字符
size_t notfound = str.find_first_not_of("0123456789"); // 查找非数字字符

5. 字符串修改

cpp 复制代码
str.append(" World");          // 追加字符串
str.push_back('!');            // 追加单个字符
str.insert(5, " Beautiful");   // 在指定位置插入
str.erase(5, 10);              // 删除从位置5开始的10个字符
str.replace(0, 5, "Hi");       // 替换从位置0开始的5个字符

6. 字符串比较

cpp 复制代码
bool equal = (str1 == str2);   // 直接比较
int result = str1.compare(str2); // 返回0表示相等,<0表示str1小,>0表示str1大
bool starts = str.starts_with("Hello"); // C++20 检查前缀
bool ends = str.ends_with("World");     // C++20 检查后缀

7. 子串操作

cpp 复制代码
string sub = str.substr(0, 5);     // 从位置0开始取5个字符
string sub2 = str.substr(6);       // 从位置6开始到结尾

8. 字符串转换

cpp 复制代码
// 数字转字符串
string num_str = to_string(123);

// 字符串转数字
int num = stoi("456");
double d = stod("3.14");
long l = stol("1000000");

// 大小写转换
transform(str.begin(), str.end(), str.begin(), ::tolower);
transform(str.begin(), str.end(), str.begin(), ::toupper);

9. 字符串流处理

cpp 复制代码
// 字符串分割
stringstream ss("apple,banana,orange");
string item;
while (getline(ss, item, ',')) {
    cout << item << endl;
}

// 格式化字符串
stringstream ss2;
ss2 << "Name: " << name << ", Age: " << age;
string result = ss2.str();

10. 字符串清理和修剪

cpp 复制代码
// 去除前后空格(自定义函数)
string trim(const string& str) {
    size_t start = str.find_first_not_of(" \t\n\r");
    size_t end = str.find_last_not_of(" \t\n\r");
    return (start == string::npos) ? "" : str.substr(start, end - start + 1);
}

常用模式速记

1. 字符串分割

cpp 复制代码
vector<string> split(const string& str, char delimiter) {
    vector<string> tokens;
    stringstream ss(str);
    string token;
    while (getline(ss, token, delimiter)) {
        tokens.push_back(token);
    }
    return tokens;
}

2. 字符串替换

cpp 复制代码
string replace_all(string str, const string& from, const string& to) {
    size_t start_pos = 0;
    while ((start_pos = str.find(from, start_pos)) != string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length();
    }
    return str;
}

3. 检查字符串内容

cpp 复制代码
bool is_number(const string& str) {
    return !str.empty() && all_of(str.begin(), str.end(), ::isdigit);
}

bool contains(const string& str, const string& substring) {
    return str.find(substring) != string::npos;
}

完整示例:综合字符串操作

cpp 复制代码
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    // 创建和初始化
    string text = "Hello World, Welcome to C++ Programming!";
    
    // 基本信息
    cout << "长度: " << text.length() << endl;
    cout << "是否为空: " << text.empty() << endl;
    
    // 查找
    size_t pos = text.find("C++");
    if (pos != string::npos) {
        cout << "找到C++在位置: " << pos << endl;
    }
    
    // 修改
    text.replace(pos, 3, "Python");
    cout << "替换后: " << text << endl;
    
    // 大小写转换
    transform(text.begin(), text.end(), text.begin(), ::tolower);
    cout << "小写: " << text << endl;
    
    // 字符串分割
    string data = "apple,banana,orange,grape";
    stringstream ss(data);
    string fruit;
    cout << "水果列表: ";
    while (getline(ss, fruit, ',')) {
        cout << fruit << " ";
    }
    cout << endl;
    
    return 0;
}

速记口诀

字符串,<string> 头;

创建拼接最常用;

查找用 find,替换用 replace

流处理,分割强;

大小写,transform


下次再遇到字符串处理,直接看这份笔记就行,不用再到处查文档了!记住:多练习才是掌握的关键。

相关推荐
一 乐6 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
码事漫谈7 小时前
Protocol Buffers 编码原理深度解析
后端
码事漫谈7 小时前
gRPC源码剖析:高性能RPC的实现原理与工程实践
后端
踏浪无痕9 小时前
AI 时代架构师如何有效成长?
人工智能·后端·架构
程序员小假9 小时前
我们来说一下无锁队列 Disruptor 的原理
java·后端
武子康10 小时前
大数据-209 深度理解逻辑回归(Logistic Regression)与梯度下降优化算法
大数据·后端·机器学习
maozexijr11 小时前
Rabbit MQ中@Exchange(durable = “true“) 和 @Queue(durable = “true“) 有什么区别
开发语言·后端·ruby
源码获取_wx:Fegn089511 小时前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计
独断万古他化11 小时前
【Spring 核心: IoC&DI】从原理到注解使用、注入方式全攻略
java·后端·spring·java-ee
毕设源码_郑学姐11 小时前
计算机毕业设计springboot基于HTML5的酒店预订管理系统 基于Spring Boot框架的HTML5酒店预订管理平台设计与实现 HTML5与Spring Boot技术驱动的酒店预订管理系统开
spring boot·后端·课程设计