21xrx.com
2024-06-03 06:04:16 Monday
登录
文章检索 我的文章 写文章
C++字符串去除空格方法
2023-07-05 09:45:14 深夜i     --     --
C++ 字符串 去除 空格 方法

在C++编程语言中,字符串是一种常用的数据类型。在处理字符串过程中,有时需要去除其中的空格。下面介绍几种C++字符串去除空格的方法。

1. 使用isspace()函数

isspace()函数用于判断一个字符是否为空格。可通过循环遍历字符串,将字符串中的空格去除。


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str = " C++ string remove space ";

  string res;

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

  {

    if (!isspace(str[i]))

      res += str[i];

  }

  cout << res << endl;

  return 0;

}

2. 使用stringstream流

C++中的stringstream是一个基于串的流,可用于将字符串转换为其他类型的数据。可通过此流去除字符串中的空格。


#include <iostream>

#include <string>

#include <sstream>

using namespace std;

int main()

{

  string str = " C++ string remove space ";

  stringstream ss(str);

  string res;

  while (ss >> str)

    res += str;

  cout << res << endl;

  return 0;

}

3. 使用STL中的remove函数

STL中的remove函数可移除容器中指定的元素。可用此函数去除字符串中的空格。


#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

  string str = " C++ string remove space ";

  str.erase(remove(str.begin(), str.end(), ' '), str.end());

  cout << str << endl;

  return 0;

}

以上是C++字符串去除空格的几种方法,根据具体情况选择不同的方法进行处理。

  
  

评论区

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