21xrx.com
2025-04-06 10:12:39 Sunday
文章检索 我的文章 写文章
C++中如何删除字符串中的空格?
2023-06-24 11:21:07 深夜i     14     0
C++ 删除 字符串 空格

在C++中,要删除字符串中的空格,可以使用标准库中的字符串处理函数和算法。

一种方法是使用C++11中的新特性——范围循环(range-based loop)和C++标准算法库中的remove_if算法,该算法可以在不移动元素的情况下删除满足特定条件的元素(即空格字符)。

以下是一个使用C++11范围循环和remove_if算法来删除字符串中空格字符的示例代码:

#include <string>
#include <algorithm>
std::string remove_spaces(const std::string& str) {
  std::string result;
  // 使用范围循环遍历字符串中的每个字符
  for (char c : str) {
    // 如果字符不是空格,将其添加到结果字符串中
    if (c != ' ') {
      result += c;
    }
  }
  // remove_if算法将空格字符移动到末尾并返回一个迭代器,指向新的末尾位置
  auto new_end = std::remove_if(result.begin(), result.end(), [](char c) return c == ' '; );
  // 使用erase方法删除新的末尾位置及其之后的字符
  result.erase(new_end, result.end());
  return result;
}
int main() {
  std::string str = "hello world";
  std::string new_str = remove_spaces(str);
  std::cout << new_str << std::endl; // 输出"helloworld"
  return 0;
}

另一种方法是使用string类的成员函数erase和remove方法,该方法也可以有效地删除字符串中的空格,但性能可能不如使用C++标准算法库中的remove_if算法。

以下是使用string类的成员函数erase和remove方法来删除字符串中空格字符的示例代码:

#include <string>
#include <algorithm>
std::string remove_spaces(const std::string& str) {
  std::string result = str;
  // 使用remove方法将空格字符移动到末尾
  result.erase(std::remove(result.begin(), result.end(), ' '), result.end());
  return result;
}
int main() {
  std::string str = "hello world";
  std::string new_str = remove_spaces(str);
  std::cout << new_str << std::endl; // 输出"helloworld"
  return 0;
}

无论使用哪种方法,都可以在C++中轻松地删除字符串中的空格字符。

  
  

评论区