21xrx.com
2024-09-20 00:02:38 Friday
登录
文章检索 我的文章 写文章
C++如何去除字符串中的空格?
2023-06-26 22:52:01 深夜i     --     --
C++ 字符串 去除 空格 函数

在C++编程中,去除字符串中的空格是一个常见的需求。有时候我们需要对文本进行处理,但是这些文本中存在一些不必要的空格,这时候我们就需要将它们移除掉。

具体的实现方法如下:

1. 使用STL字符串库中的函数erase和remove_if,erase函数用于删除指定位置的字符,remove_if函数用于删除符合条件的字符。以下是一个示例代码:


#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

string removeSpaces(string str)

{

  str.erase(remove_if(str.begin(), str.end(), ::isspace), str.end());

  return str;

}

int main()

{

  string s = "  This is a test string.  ";

  s = removeSpaces(s);

  cout << s << endl; //输出:Thisisateststring.

  return 0;

}

2. 使用C语言的函数库中的函数来实现。在C语言的头文件ctype.h中有些函数可以判断一个字符是否为空格,比如isspace函数。利用这个函数,我们就可以遍历字符串将其中的空格删去。


#include <iostream>

#include <string>

#include <ctype.h>

using namespace std;

string removeSpaces(string str)

{

  string res = "";

  for (int i = 0; i < str.size(); i++)

  {

    if (!isspace(str[i]))

    {

      res += str[i];

    }

  }

  return res;

}

int main()

{

  string s = "  This is a test string.  ";

  s = removeSpaces(s);

  cout << s << endl; //输出:Thisisateststring.

  return 0;

}

使用任何一种方法,都可以去除字符串中的空格。具体使用哪种方法取决于个人编程习惯和项目需求。无论哪种方法,都需要理解函数的作用和使用方式,才能更好地利用它们解决问题。

  
  

评论区

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