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

在C++中去除字符串中的空格,可以根据需求选择不同的方法。常见的场景包括去除首尾空格、去除所有空格,或只保留单词间单个空格。以下是几种实用的实现方式。
如果想删除字符串中的所有空格,可以结合 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 或换行符。
手动实现去除字符串开头和结尾的空白字符:
立即学习“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);
}
调用示例:
std::string str = " hello world "; std::cout << "[" << trim(str) << "]"; // 输出: [hello world]
适用于格式化文本,将多个连续空格合并为一个:
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"。
如果目标是忽略所有空白并提取有效内容,可以用 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 方式。灵活组合即可满足大多数场景。
以上就是c++++中如何去除字符串中的空格_c++去除空格实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号