21xrx.com
2024-05-20 09:26:52 Monday
登录
文章检索 我的文章 写文章
C++如何去除字符串收尾空格?
2023-07-13 08:01:28 深夜i     --     --
C++ 字符串 去除 收尾空格

在C++编程中,有时候需要对字符串进行处理,而很多情况下字符串可能会包含一些收尾空格,这些空格可能会影响程序的正常运行。因此,如何去除字符串收尾空格就成为了程序员们必须要掌握的技能之一。

常用的方法包括使用迭代器、使用字符串的成员函数、使用正则表达式等。

方法一:使用迭代器

使用迭代器的方法就是将字符串分为前后两部分,遍历前半部分的字符,找到第一个不是空格的字符,然后从该字符位置开始提取后面的字符,将其重新赋值给原字符串。最后,再遍历后半部分的字符,找到最后一个不是空格的字符,将其后面的所有字符删除即可。可以通过如下代码实现:


#include <iostream>

#include <string>

void trim(std::string &s) {

  // 找到第一个非空格字符

  auto first = s.begin();

  while (first != s.end() && std::isspace(*first)) {

    ++first;

  }

  // 找到最后一个非空格字符

  auto last = s.end();

  while (last != first && std::isspace(*--last)) {}

  s.erase(last + 1, s.end());

  s.erase(s.begin(), first);

}

int main() {

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

  trim(s);

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

  return 0;

}

方法二:使用字符串的成员函数

C++的字符串类std::string提供了一些成员函数可以方便地去除字符串收尾空格。

其中,最常用的是std::string::find_first_not_of和std::string::find_last_not_of函数,它们分别可以在字符串的前半部分和后半部分找到第一个不是空格的字符和最后一个不是空格的字符的位置,然后使用std::string::substr函数截取需要的字符串即可。代码如下:


#include <iostream>

#include <string>

void trim(std::string &s) {

  // 去除前半部分空格

  size_t pos = s.find_first_not_of(" \t\r\n");

  if (pos != std::string::npos) {

    s.erase(0, pos);

  } else {

    s.clear();

  }

  // 去除后半部分空格

  pos = s.find_last_not_of(" \t\r\n");

  if (pos != std::string::npos) {

    s.erase(pos + 1);

  }

}

int main() {

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

  trim(s);

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

  return 0;

}

方法三:使用正则表达式

使用正则表达式可以方便地去除字符串收尾空格。只需要将字符串中的空格替换为空字符串即可。代码如下:


#include <iostream>

#include <string>

#include <regex>

void trim(std::string &s) {

  // 去除前半部分空格

  s = std::regex_replace(s, std::regex("^\\s+"), "");

  // 去除后半部分空格

  s = std::regex_replace(s, std::regex("\\s+$"), "");

}

int main() {

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

  trim(s);

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

  return 0;

}

以上三种方法都可以去除字符串收尾空格,可以根据需要灵活选择使用。在实际开发中,对于长字符串来说,正则表达式的效率可能会低于前两种方法。因此,在处理大量数据时,建议使用前两种方法。

  
  

评论区

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