21xrx.com
2024-09-20 00:45:45 Friday
登录
文章检索 我的文章 写文章
如何在C++中删除空格?
2023-07-03 12:04:33 深夜i     --     --
C++ 删除 空格

在C++中删除空格是一个常见的编程任务,因为空格会占用程序的时间和空间,并且对程序的结果可能会产生不利影响。下面介绍几种常用的方法。

方法一:使用string类的erase函数

string类是C++中经常使用的字符串类,它提供了许多字符串操作函数。其中,erase函数可以用来删除字符串中的空格。具体的步骤如下:

1. 定义一个字符串变量str,并将待处理的字符串存入该变量;

2. 使用for循环遍历字符串中的每一个字符;

3. 如果当前字符是空格,则使用erase函数删除该空格。

示例代码:


#include <iostream>

#include <string>

using namespace std;

int main() {

  string str = " hello world ";

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

    if (str[i] == ' ') {

      str.erase(i, 1);

      i--;

    }

  }

  cout << str << endl; //输出结果为"helloworld"

  return 0;

}

方法二:使用标准库中的remove函数

标准库中的remove函数可以用来删除容器中指定的元素,并返回容器中删除后的新长度。使用remove函数删除字符串中的空格,具体步骤如下:

1. 定义一个字符串变量str,并将待处理的字符串存入该变量;

2. 使用remove函数删除字符串中的空格;

3. 使用erase函数来删除多余的字符。

示例代码:


#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main() {

  string str = " hello world ";

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

  cout << str << endl; //输出结果为"helloworld"

  return 0;

}

方法三:使用正则表达式

C++中也支持使用正则表达式来删除字符串中的空格。具体步骤如下:

1. 引入regex头文件;

2. 定义一个字符串变量str,并将待处理的字符串存入该变量;

3. 构造正则表达式,并使用regex_replace函数来替换空格。

示例代码:


#include <iostream>

#include <string>

#include <regex>

using namespace std;

int main() {

  string str = " hello world ";

  regex r("\\s+");

  str = regex_replace(str, r, "");

  cout << str << endl; //输出结果为"helloworld"

  return 0;

}

总结:

以上介绍了C++中删除空格的三种常见方法,分别是使用string类的erase函数、使用标准库中的remove函数以及使用正则表达式。这些方法各有优缺点,可以根据具体的情况选择使用。同时,删除空格也可以使用其他语言的方法,在实际编程中需要根据具体情况进行选择。

  
  

评论区

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