21xrx.com
2024-09-19 09:52:22 Thursday
登录
文章检索 我的文章 写文章
C++ 去除字符串空格
2023-06-29 12:52:37 深夜i     --     --
C++ 字符串 去除 空格 函数

在C++编程中,字符串处理是一项非常常见的任务。在处理字符串时,我们经常会遇到一个问题,那就是字符串中包含空格。这些空格有时需要保留,但有时我们又需要将其去掉。在本文中,我们将介绍如何使用C++去除字符串空格。

第一种方法是使用stringstream。我们可以创建一个stringstream对象,并使用其提供的流操作符来去除字符串中的空格。以下是示例代码:


#include <iostream>

#include <string>

#include <sstream>

using namespace std;

int main()

{

  string str = "  hello   world  ";

  stringstream ss(str);

  string word;

  while (ss >> word)

  

    cout << word << " ";

  

  cout << endl;

  return 0;

}

在上面的示例中,我们首先将字符串str传递给stringstream对象ss。然后,我们使用while循环和“ >> ”流操作符读取每个单词并将其打印出来。在这个过程中,所有空格都被忽略了。

第二种方法是使用C++的STL库中的算法。我们可以使用remove_if函数来去除字符串中的空格。以下是示例代码:


#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

bool isSpace(char c)

{

  return (c == ' ');

}

int main()

{

  string str = "  hello   world  ";

  str.erase(remove_if(str.begin(), str.end(), isSpace), str.end());

  cout << str << endl;

  return 0;

}

在上面的示例中,我们首先定义了一个名为isSpace的谓词函数,该函数用于判断给定字符是否为空格。接下来,我们使用STL的remove_if函数将所有空格移到字符串的末尾,并使用erase函数将它们删除。

无论是使用stringstream还是STL的算法,这两种方法都可以有效地去除字符串中的空格。选择其中一个方法取决于你的偏好和代码的应用场景。无论你选择哪种方法,希望本文能够帮助你更好地处理字符串。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复