使用remove和erase可删除所有空格,如" hello world "变为"helloworld";2. 通过find_first_not_of和find_last_not_of实现trim,去除首尾空白保留中间空格;3. 遍历字符串标记空格状态,将连续空格压缩为单个;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()); std::cout << str; // 输出: helloworld
这个方法适用于去除字符串中所有的空格字符(包括多个连续空格)。
如果只想去掉开头和结尾的空格,可以手动查找第一个和最后一个非空格字符的位置。
立即学习“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);
}
<p>// 使用示例
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 == ' ') {
if (!inSpace) {
result += c;
inSpace = true;
}
} else {
result += c;
inSpace = false;
}
}
return result;
}
例如输入:"a b c",输出为:"a b c"。
如果目标是提取非空字段,可以用 std::stringstream 自动跳过空白。
示例代码:#include <sstream>
std::string str = " hello world cpp ";
std::stringstream ss(str);
std::string word, result;
<p>while (ss >> word) {
if (!result.empty()) result += " ";
result += word;
}
std::cout << result; // 输出: hello world cpp
这种方式天然过滤所有空白,并以单空格连接单词,适合清洗用户输入。
基本上就这些常用方法。根据实际需要选择:全部删除用 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号