21xrx.com
2025-03-26 12:53:31 Wednesday
文章检索 我的文章 写文章
C++实现字符串首尾空格去除
2023-07-07 00:08:35 深夜i     --     --
C++ 字符串处理 空格 首尾 去除

  return c == ' ' || c == 't' || c == 'r' || c == 'n';

  return c == ' ' || c == 't' || c == 'r' || c == 'n';

在日常的编程中,我们经常需要对字符串进行处理以达到特定的效果。比如有时候需要把字符串的首尾空格去掉,但是直接去除空格并不是那么简单。本篇文章将介绍如何使用C++实现字符串首尾空格去除的方法。

首先,我们需要确定要去除的是哪些字符。字符串中的空格有很多种形式,比如空格、制表符、回车符等等。因此,我们需要定义一个函数来判断一个字符是否为空白字符。下面是一个简单的实现:

bool is_whitespace(char c) {
  return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}

接下来,我们需要实现一个函数来去除字符串的首尾空格。做法是:先找到第一个不为空格的字符和最后一个不为空格的字符的位置,然后将它们之间的字符复制到一个新的字符串中。下面是实现代码:

std::string trim(const std::string& str) {
  std::size_t start = 0;
  while (start < str.length() && is_whitespace(str[start])) {
    start++;
  }
  std::size_t end = str.length() - 1;
  while (end > start && is_whitespace(str[end]))
    end--;
  
  return str.substr(start, end - start + 1);
}

在这个函数中,我们使用了字符串类的substr()方法来提取字符子串。这个方法的第一个参数是要提取的子串的起始位置,第二个参数是要提取的子串的长度。因此,我们需要计算出起始位置和长度。

在主函数中,我们可以测试一下这个函数的效果:

#include <iostream>
#include <string>
bool is_whitespace(char c) {
  return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
std::string trim(const std::string& str) {
  std::size_t start = 0;
  while (start < str.length() && is_whitespace(str[start])) {
    start++;
  }
  std::size_t end = str.length() - 1;
  while (end > start && is_whitespace(str[end]))
    end--;
  
  return str.substr(start, end - start + 1);
}
int main() {
  std::string str = " \t \t hello, world! \n\n\n";
  std::cout << "[" << str << "]" << std::endl;
  std::cout << "[" << trim(str) << "]" << std::endl;
  return 0;
}

运行结果如下:

[     hello, world!
]
[hello, world!]

可以看到,我们成功地将字符串的首尾空格去除了。这个方法不仅简单易用,而且效率也非常高。需要去除字符串的首尾空格时,可以直接调用这个函数即可。

  
  

评论区