首页 > 后端开发 > C++ > 正文

C++ string类操作 常用字符串处理方法

P粉602998670
发布: 2025-08-22 11:38:01
原创
962人浏览过
C++ string类提供构造、赋值、访问、查找、替换等丰富操作,通过实例演示了长度获取、子串提取、内容替换等功能,并推荐使用stringstream或reserve提升大量字符串拼接效率,同时介绍string::npos用于表示查找失败,以及stoi/to_string等函数实现字符串与数值转换。

c++ string类操作 常用字符串处理方法

C++

string
登录后复制
类提供了丰富的功能,用于处理字符串。 掌握这些方法能极大提高代码效率和可读性。下面将介绍一些常用的字符串处理方法,并结合实际例子进行说明。

解决方案

C++

string
登录后复制
类提供了强大的字符串操作能力。以下是一些常用的方法:

  • 构造函数:
    string s;
    登录后复制
    (默认构造,空字符串),
    string s = "hello";
    登录后复制
    (用C风格字符串初始化),
    string s(n, 'a');
    登录后复制
    (用n个字符 'a' 初始化),
    string s(another_string);
    登录后复制
    (拷贝构造).
  • 赋值:
    s = "world";
    登录后复制
    ,
    s.assign("C++");
    登录后复制
    ,
    s.assign(another_string);
    登录后复制
    ,
    s.assign(n, 'b');
    登录后复制
    .
  • 访问:
    s[i]
    登录后复制
    (访问索引为 i 的字符,不进行越界检查),
    s.at(i)
    登录后复制
    (访问索引为 i 的字符,进行越界检查,越界会抛出异常).
  • 长度:
    s.length()
    登录后复制
    s.size()
    登录后复制
    (返回字符串长度).
  • 容量:
    s.capacity()
    登录后复制
    (返回当前分配的内存大小,可能大于字符串长度),
    s.reserve(n)
    登录后复制
    (预分配至少能容纳 n 个字符的空间,避免频繁重新分配内存),
    s.shrink_to_fit()
    登录后复制
    (释放多余的内存).
  • 添加:
    s += "!";
    登录后复制
    ,
    s.append(" more");
    登录后复制
    ,
    s.push_back('c');
    登录后复制
    .
  • 插入:
    s.insert(pos, "new");
    登录后复制
    (在 pos 位置插入字符串 "new"),
    s.insert(pos, another_string);
    登录后复制
    ,
    s.insert(pos, n, 'x');
    登录后复制
    (在 pos 位置插入 n 个字符 'x').
  • 删除:
    s.erase(pos, len);
    登录后复制
    (从 pos 位置开始删除 len 个字符),
    s.clear()
    登录后复制
    (清空字符串).
  • 替换:
    s.replace(pos, len, "replacement");
    登录后复制
    (从 pos 位置开始,替换 len 个字符为 "replacement"),
    s.replace(pos, len, another_string);
    登录后复制
    .
  • 查找:
    s.find("substring");
    登录后复制
    (查找 "substring" 第一次出现的位置,返回索引,找不到返回
    string::npos
    登录后复制
    ),
    s.rfind("substring");
    登录后复制
    (从后往前查找),
    s.find_first_of("chars");
    登录后复制
    (查找第一个出现在 "chars" 中的字符的位置),
    s.find_last_of("chars");
    登录后复制
    (查找最后一个出现在 "chars" 中的字符的位置).
  • 子串:
    s.substr(pos, len);
    登录后复制
    (返回从 pos 位置开始,长度为 len 的子串).
  • 比较:
    s1 == s2
    登录后复制
    ,
    s1 != s2
    登录后复制
    ,
    s1 < s2
    登录后复制
    ,
    s1 > s2
    登录后复制
    ,
    s.compare(another_string);
    登录后复制
    (返回 0 表示相等,小于 0 表示 s 小于 another_string,大于 0 表示 s 大于 another_string).
  • 转换为C风格字符串:
    s.c_str()
    登录后复制
    (返回指向C风格字符串的指针,注意生命周期问题).
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";

    // 长度
    std::cout << "Length: " << str.length() << std::endl;

    // 查找
    size_t pos = str.find("World");
    if (pos != std::string::npos) {
        std::cout << "'World' found at position: " << pos << std::endl;
    }

    // 子串
    std::string sub = str.substr(7, 5); // "World"
    std::cout << "Substring: " << sub << std::endl;

    // 替换
    str.replace(7, 5, "C++");
    std::cout << "Replaced string: " << str << std::endl;

    return 0;
}
登录后复制

如何高效地拼接大量字符串?

使用

+=
登录后复制
append
登录后复制
在循环中拼接字符串,尤其是在拼接大量字符串时,效率可能较低,因为每次操作都可能涉及内存重新分配。 更好的做法是预先分配足够的内存,或者使用
stringstream
登录后复制

立即学习C++免费学习笔记(深入)”;

法语写作助手
法语写作助手

法语助手旗下的AI智能写作平台,支持语法、拼写自动纠错,一键改写、润色你的法语作文。

法语写作助手 31
查看详情 法语写作助手
#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::stringstream ss;
    for (int i = 0; i < 1000; ++i) {
        ss << "Number: " << i << " ";
    }
    std::string result = ss.str();
    std::cout << result.substr(0, 100) << "..." << std::endl; // 输出部分结果
    return 0;
}
登录后复制

使用

stringstream
登录后复制
避免了频繁的内存重新分配,提高了效率。 另一种方法是使用
reserve
登录后复制
预先分配足够的内存。

string::npos
登录后复制
是什么?有什么用?

string::npos
登录后复制
string
登录后复制
类的一个静态成员常量,通常被定义为
-1
登录后复制
size_t
登录后复制
类型的最大值。 它表示“未找到”或“不存在”的位置。
find
登录后复制
函数在查找失败时会返回
string::npos
登录后复制

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello";
    size_t pos = str.find("World");

    if (pos == std::string::npos) {
        std::cout << "'World' not found in the string." << std::endl;
    } else {
        std::cout << "'World' found at position: " << pos << std::endl;
    }

    return 0;
}
登录后复制

如何将
string
登录后复制
转换为
int
登录后复制
float
登录后复制
?反之呢?

C++11 提供了

std::stoi
登录后复制
,
std::stof
登录后复制
,
std::stod
登录后复制
等函数用于将字符串转换为数值类型。 反过来,可以使用
std::to_string
登录后复制
将数值类型转换为字符串。

#include <iostream>
#include <string>

int main() {
    std::string str_int = "123";
    std::string str_float = "3.14";

    int num_int = std::stoi(str_int);
    float num_float = std::stof(str_float);

    std::cout << "Integer: " << num_int << std::endl;
    std::cout << "Float: " << num_float << std::endl;

    std::string new_str_int = std::to_string(num_int * 2);
    std::string new_str_float = std::to_string(num_float * 2);

    std::cout << "New Integer String: " << new_str_int << std::endl;
    std::cout << "New Float String: " << new_str_float << std::endl;

    return 0;
}
登录后复制

需要注意的是,如果字符串不能正确转换为数值类型,

std::stoi
登录后复制
,
std::stof
登录后复制
,
std::stod
登录后复制
会抛出异常,因此需要进行适当的错误处理。

以上就是C++ string类操作 常用字符串处理方法的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号