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

在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(" \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]
这种方法保留中间空格,只清理两端空白,常用于输入处理。
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 自动跳过空白。
示例代码:#includestd::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。实现简单,效率也不错。











