c++怎么删除字符串中的空格_c++去除字符串空格方法

使用remove和erase可删除所有空格,如” hello world “变为”helloworld”;2. 通过find_first_not_of和find_last_not_of实现trim,去除首尾空白保留中间空格;3. 遍历字符串标记空格状态,将连续空格压缩为单个;4. 利用stringstream自动跳过空白并以单空格连接单词,适合清洗输入。根据需求选择方法即可。

c++怎么删除字符串中的空格_c++去除字符串空格方法

在C++中删除字符串中的空格有多种方法,根据需求可以选择去除首尾空格、所有空格,或连续空格压缩为单个空格等。下面介绍几种常用且实用的方法。

1. 使用标准库算法 remove 和 erase(去除所有空格)

这是最简洁高效的方法之一,利用 std::remove 将空格“移除”到字符串末尾,再用 erase 删除它们。

示例代码:

#include #include #include 

std::string str = " hello world ";// 删除所有空格str.erase(std::remove(str.begin(), str.end(), ' '), str.end());std::cout << str; // 输出: helloworld

这个方法适用于去除字符串中所有的空格字符(包括多个连续空格)。

2. 去除首尾空格(trim 操作)

如果只想去掉开头和结尾的空格,可以手动查找第一个和最后一个非空格字符的位置。

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

示例代码:

std::string trim(const std::string& str) {    size_t start = str.find_first_not_of(" tnr");    if (start == std::string::npos) return ""; // 全是空白    size_t end = str.find_last_not_of(" tnr");    return str.substr(start, end - start + 1);}

// 使用示例std::string str = " hello world ";std::cout << "[" << trim(str) << "]"; // 输出: [hello world]

这种方法保留中间空格,只清理两端空白,常用于输入处理。

3. 去除多余空格,保留单词间单个空格

有时希望将多个连续空格合并成一个,比如格式化文本时。

示例代码:

std::string compressSpaces(const std::string& str) {    std::string result;    bool inSpace = false;    for (char c : str) {        if (c == ' ') {            if (!inSpace) {                result += c;                inSpace = true;            }        } else {            result += c;            inSpace = false;        }    }    return result;}

例如输入:"a b c",输出为:"a b c"

4. 使用 stringstream 去除多余空格(适合分词场景)

如果目标是提取非空字段,可以用 std::stringstream 自动跳过空白。

示例代码:

#include std::string str = "  hello    world  cpp  ";std::stringstream ss(str);std::string word, result;

while (ss >> word) {if (!result.empty()) result += " ";result += word;}std::cout << result; // 输出: hello world cpp

这种方式天然过滤所有空白,并以单空格连接单词,适合清洗用户输入。

基本上就这些常用方法。根据实际需要选择:全部删除用 remove+erase,去头尾用 trim,整理格式可用压缩或 stringstream。实现简单,效率也不错。

以上就是c++++怎么删除字符串中的空格_c++去除字符串空格方法的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1481254.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 05:20:00
下一篇 2025年12月19日 05:20:16

相关推荐

发表回复

登录后才能评论
关注微信