去除字符串空格有多种方法:1. 用std::remove和erase删除所有空格,结果为”helloworld”;2. 自定义trim函数去除首尾空白,保留中间空格;3. compressSpaces函数将连续空白合并为单个空格;4. 使用stringstream按单词提取,自动忽略多余空白,重组为规范字符串。

在C++中去除字符串中的空格,可以根据需求选择不同的方法。常见的场景包括去除首尾空格、去除所有空格,或只保留单词间单个空格。以下是几种实用的实现方式。
1. 使用标准库算法 remove 和 erase 去除所有空格
如果想删除字符串中的所有空格,可以结合 std::remove 和 erase 方法:
#include <algorithm> #include <string> #include <iostream> <p>std::string str = " hello world "; str.erase(std::remove(str.begin(), str.end(), ' '), str.end()); // 结果: "helloworld"</p>
这个方法会把所有空格字符 ‘ ‘ 删除。注意:只针对普通空格,不包括制表符 \t 或换行符。
2. 去除首尾空格(trim)
手动实现去除字符串开头和结尾的空白字符:
立即学习“C++免费学习笔记(深入)”;
std::string trim(const std::string& str) {
size_t start = str.find_first_not_of(" \t\n\r");
if (start == std::string::npos) return ""; // 全是空白
size_t end = str.find_last_not_of(" \t\n\r");
return str.substr(start, end - start + 1);
}
调用示例:
人声去除
23
用强大的AI算法将声音从音乐中分离出来
23
查看详情
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 == ' ' || c == '\t' || c == '\n') {
if (!inSpace) {
result += ' ';
inSpace = true;
}
} else {
result += c;
inSpace = false;
}
}
// 去掉末尾可能多余的空格
if (!result.empty() && result.back() == ' ') {
result.pop_back();
}
return result;
}
输入:” hello world\t\n test “,输出:”hello world test”。
4. 使用 stringstream 按单词提取(自动跳过空格)
如果目标是忽略所有空白并提取有效内容,可以用 std::stringstream:
#include <sstream>
#include <vector>
<p>std::string str = " hello world ";
std::stringstream ss(str);
std::string word;
std::string result;</p><p>while (ss >> word) {
if (!result.empty()) result += " ";
result += word;
}
// 结果: "hello world"</p>
这种方法天然跳过所有空白,适合重组句子。
基本上就这些常见方法。根据具体需求选择:删全部空格用 remove-erase;去首尾用 trim;整理格式可用压缩或 stringstream 方式。灵活组合即可满足大多数场景。
相关标签:
word go c++ ios 标准库 字符串 算法
大家都在看:
c++中如何实现多态_c++多态实现方法
c++中如何传递字符串给函数_c++字符串传参方法
c++中如何生成指定范围的随机数_c++范围随机数生成方法
c++中如何遍历map_c++遍历map容器的几种方法
c++中怎么实现一个线程池_C++高性能线程池设计与实现
c++中如何传递字符串给函数_c++字符串传参方法
c++中如何生成指定范围的随机数_c++范围随机数生成方法
c++中如何遍历map_c++遍历map容器的几种方法
c++中怎么实现一个线程池_C++高性能线程池设计与实现
本站资料仅供学习交流使用请勿商业运营,严禁从事违法,侵权等任何非法活动,否则后果自负!
THE END

































暂无评论内容