跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客我的书AI学习GitHub 精选镜像AI工具UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
C++算法

C++ string 类详解:初始化、遍历与常用函数

C++ string 类是处理文本的核心工具。本文涵盖初始化方式(默认、直接构造、拷贝)、三种遍历方法(下标、范围 for、迭代器)及容量管理(size 与 capacity 区别)。重点解析常用成员函数如 append、substr、find 和 replace,并指出 cin 与 getline 混用的常见陷阱。通过实际代码示例展示内存分配机制与字符串操作细节,帮助开发者高效掌握标准库用法。

魔法巫师发布于 2026/2/23更新于 2026/11/592 浏览

一、string 的初始化与遍历

在使用 std::string 之前,记得包含 <string> 头文件。它支持 cin 输入和 cout 输出,是处理文本的核心工具。

1. string 的初始化

这里主要介绍三种最常用的初始化方式。

默认初始化 创建一个空字符串。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1;
    cout << s1 << endl;
    return 0;
}

直接构造 显式调用构造函数,传入 C 风格字符串。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("Hello world");
    cout << s1 << endl;
    return 0;
}

拷贝构造 利用已有的 string 对象创建一个副本。

#include <iostream>
#include <string>
using namespace std;

int main {
    string s1;
    cin >> s1;
    ;
    cout << s2 << endl;
     ;
}
()
string s2(s1)
return
0

2. string 的遍历

2.1 下标访问

size() 和 length() 都返回字符个数(字节数,不含末尾隐藏的 \0)。早期 length() 独立存在,后来为了符合 STL 容器统一接口规范增加了 size(),建议优先使用 size()。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    cout << s1.size() << endl;
    cout << s1.length() << endl;
    return 0;
}

operator[] 重载了方括号运算符,用于读取或修改字符。注意越界访问可能导致未定义行为或读取垃圾数据。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    cout << s1[5] << endl; // 访问下标为 5 的元素
    s1[6] = 'M';           // 修改下标为 6 的元素
    cout << s1 << endl;
    return 0;
}

下标遍历示例:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    for (int i = 0; i < s1.size(); i++) {
        cout << s1[i] << " ";
    }
    cout << endl;
    return 0;
}
2.2 范围 for 循环

C++11 引入的范围 for 循环简化了遍历过程,底层通常替换为迭代器实现。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    for (auto e : s1) {
        cout << e << " ";
    }
    cout << endl;
    return 0;
}

注意: 如果直接使用 auto e,变量是值拷贝,修改 e 不会影响原字符串。若需修改,应使用引用 auto &e。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    for (auto &e : s1) {
        e = 'm';
        cout << e << " ";
    }
    cout << endl;
    cout << s1 << endl;
    return 0;
}
2.3 迭代器遍历

迭代器充当通用指针,屏蔽底层实现细节。begin() 指向首元素,end() 指向尾元素之后。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    string::iterator it = s1.begin();
    while (it != s1.end()) {
        cout << *it << " ";
        it++;
    }
    cout << endl;
    return 0;
}

反向迭代器 rbegin() 和 rend() 可用于倒序遍历。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    string::reverse_iterator it = s1.rbegin();
    while (it != s1.rend()) {
        cout << *it << " ";
        it++;
    }
    cout << endl;
    return 0;
}

二、有关 string 容量的函数

string 底层由指针、大小(Size)、容量(Capacity)及内部缓冲区组成。Size 记录有效字符数,Capacity 记录分配总空间。

1. capacity

容量不一定等于 Size,额外空间允许添加新字符而不必立即重新分配内存。不同编译器扩容策略可能不同(如 VS 默认先开 16 字节缓冲,超出后按倍数增长)。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    size_t sz = s1.capacity();
    cout << "capacity changed: " << sz << '\n';
    cout << "making s grow:\n";
    for (int i = 0; i < 100; ++i) {
        s1.push_back('c');
        if (sz != s1.capacity()) {
            sz = s1.capacity();
            cout << "capacity changed: " << sz << '\n';
        }
    }
    cout << endl;
    return 0;
}

reserve 提前预留空间,避免频繁扩容开销。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    s1.reserve(100);
    cout << s1.capacity() << endl;
    return 0;
}

2. 其它容量相关函数

clear:清空内容,长度变为 0。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    s1.clear();
    cout << s1.size() << endl;
    return 0;
}

empty:判断是否为空。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    s1.clear();
    if (s1.empty()) {
        cout << "字符串为空" << endl;
    }
    return 0;
}

三、常用的成员函数

1. operator+=

在字符串末尾追加内容。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    cout << s1 << endl;
    s1 += " Hello kong";
    cout << s1 << endl;
    return 0;
}

2. push_back

在末尾附加单个字符。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    cout << s1 << endl;
    s1.push_back(' ');
    s1.push_back('m');
    cout << s1 << endl;
    return 0;
}

3. append

添加字符串或子串。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    s1.append("geerghre");
    cout << s1 << endl;
    return 0;
}

截取并添加:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1 = "I love ";
    string s2 = "C++ Programming";
    // 从 s2 索引 4 开始取 7 个字符 "Program"
    s1.append(s2, 4, 7);
    cout << s1 << endl;
    return 0;
}

4. substr

生成子串。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    string s2 = s1.substr(5);
    cout << s2 << endl;
    return 0;
}

5. find 与 replace

find:搜索首次出现位置,未找到返回 npos。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("HelloWorld");
    size_t pos = s1.find('#');
    if (pos == string::npos) {
        cout << "没有这个字符串" << endl;
    }
    return 0;
}

replace:替换指定范围的字符。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1("Hello.Worl.dtdjd.dhsdjt");
    size_t pos = s1.find('.');
    while (pos != string::npos) {
        s1.replace(pos, 1, "##");
        pos = s1.find('.', pos + 2);
    }
    cout << s1 << endl;
    return 0;
}

6. getline

处理含空格的整行输入。注意混用 cin >> 时残留换行符的问题。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1, s2;
    cout << "请输入 s1 的字符串:";
    cin >> s1;
    cout << "s1 的字符串为:" << s1 << endl << endl;
    
    // 清除缓冲区中的换行符
    cin.ignore(); 
    
    cout << "请输入 s2 的字符串:";
    getline(cin, s2);
    cout << "s2 的字符串为:" << s2 << endl;
    return 0;
}

如需查阅更多官方文档,可参考 cplusplus.com/string。

目录

  1. 一、string 的初始化与遍历
  2. 1. string 的初始化
  3. 2. string 的遍历
  4. 2.1 下标访问
  5. 2.2 范围 for 循环
  6. 2.3 迭代器遍历
  7. 二、有关 string 容量的函数
  8. 1. capacity
  9. 2. 其它容量相关函数
  10. 三、常用的成员函数
  11. 1. operator+=
  12. 2. push_back
  13. 3. append
  14. 4. substr
  15. 5. find 与 replace
  16. 6. getline

更多推荐文章

查看全部
  • 前后端共用校验规则方案:后端为最终权威
  • Java 数据结构:二叉树与哈希表详解
  • 9 篇必读的大模型论文
  • ChatGLM-6B 智能写作助手开发指南
  • MiroFish:基于多智能体的群体智能模拟引擎
  • C++多线程编程:测试 Windows 下最大线程数
  • 滑动窗口算法进阶:水果成篮与最小覆盖子串
  • C++ 继承机制详解:从基础到多继承
  • HivisionIDPhotos 开源 AI 证件照工具功能解析与部署指南
  • 循环神经网络(RNN)与序列数据处理实战
  • 文心一言大模型使用指南:指令编写与进阶应用
  • C++ 继承机制详解:从基础到多继承与组合
  • Spring Boot 数据仓库与 ETL 工具集成
  • 5 本大模型入门书籍推荐:从基础到应用实践
  • ToDesk ToClaw:基于 OpenClaw 的零门槛 AI 桌面自动化方案
  • 基于 AI 辅助的在线图书借阅平台设计与实现
  • C++ 二叉搜索树:增删查改与 key/value 场景实现
  • 自动化测试面试题:Selenium 与 TestNG 核心判断题
  • 论文和文章去 AI 痕迹技巧:如何让 AI 生成内容更具“人味儿”
  • Mac 安装工具时如何区分 x86 与 arm64 架构

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • Gemini 图片去水印

    基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online

  • HTML转Markdown

    将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online