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

C++ 函数的 STL 函数有哪些用于字符串处理?

WBOY
发布: 2024-10-07 11:03:01
原创
583人浏览过

c++++ stl 中用于字符串处理的主要函数包括:复制 (std::string::copy())、查找 (std::string::find())、替换 (std::string::replace())、提取子字符串 (std::string::substr())、字符串到整数转换 (std::stoi())、整数到字符串转换 (std::to_string())。此外,还提供了一些辅助函数,如单词统计例程中使用的 isalpha() 和 tolower()。

C++ 函数的 STL 函数有哪些用于字符串处理?

C++ STL 中用于字符串处理的函数

C++ 标准模板库 (STL) 为字符串处理提供了广泛的函数,简化和增强字符串操作。以下是几个最常用的 STL 字符串函数:

  • std::string::copy():将字符串的全部或部分复制到目标字符数组中。
std::string str = "Hello world";
char dest[12];
str.copy(dest, 12); // 复制 "Hello worl" 到 dest,留出空字符
登录后复制
  • std::string::find():搜索子字符串在字符串中的第一个出现位置。
std::string str = "This is a sample string";
size_t pos = str.find("sample"); // pos = 10
登录后复制
  • std::string::replace():将字符串中指定的子字符串替换为新字符串。
std::string str = "C++ is a powerful language";
str.replace(0, 3, "STL"); // 替换 "C++" 为 "STL"
登录后复制
  • std::string::substr():从字符串中提取子字符串。
std::string str = "This is a string";
std::string substring = str.substr(4, 6); // substring = "is a"
登录后复制
  • std::stoi():将字符串转换为整数。
std::string num = "123";
int n = std::stoi(num); // n = 123
登录后复制
  • std::to_string():将整数转换为字符串。
int n = 456;
std::string num = std::to_string(n); // num = "456"
登录后复制

实战案例:单词统计

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

以下是一个使用 STL 字符串函数实现单词统计的小示例:

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main() {
    string str = "This is a sample string, with multiple words";

    // 创建单词计数 map
    map<string, int> wordCount;

    // 分割字符串并更新计数
    string word;
    for (char c : str) {
        if (isalpha(c)) {
            word += tolower(c);
        } else if (!word.empty()) {
            wordCount[word]++;
            word.clear();
        }
    }

    // 打印单词计数
    for (auto& [word, count] : wordCount) {
        cout << word << ": " << count << endl;
    }

    return 0;
}
登录后复制

以上就是C++ 函数的 STL 函数有哪些用于字符串处理?的详细内容,更多请关注php中文网其它相关文章!

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

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

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

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