21xrx.com
2024-09-20 00:58:25 Friday
登录
文章检索 我的文章 写文章
C++如何去除字符串中的空格?
2023-07-03 05:04:11 深夜i     --     --
C++ 字符串 去除空格

在C++中,可以通过使用字符串函数和循环来去除字符串中的空格。

一种方法是使用C++中的字符串函数,例如`std::remove_if()`和`std::isspace()`。`std::isspace()`函数是用来检查字符是否为空格符,而`std::remove_if()`函数可以用来从字符串中删除指定的字符。

另一种方法是使用循环来遍历字符串中的每个字符,并检查它是否为空格符。如果是,则将该字符从字符串中删除,否则跳过。

以下是使用方法一的示例代码:


#include <iostream>

#include <algorithm>

#include <string>

int main() {

  std::string str = "Hello,  World!";

  // remove_if with isspace to remove spaces

  str.erase(std::remove_if(str.begin(), str.end(), [](char c){

    return std::isspace(c);

  }), str.end());

  std::cout << str << std::endl; // "Hello,World!"

  return 0;

}

以下是使用方法二的示例代码:


#include <iostream>

#include <string>

int main() {

  std::string str = "Hello,  World!";

  // loop to remove spaces

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

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

      str.erase(i, 1);

      i--;

    }

  }

  std::cout << str << std::endl; // "Hello,World!"

  return 0;

}

用这两种方法都可以去除字符串中的空格,选择哪种方法取决于你的个人喜好和代码上下文。

  
  

评论区

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