21xrx.com
2024-09-20 05:55:55 Friday
登录
文章检索 我的文章 写文章
如何在C++中去掉字符串首位的空格
2023-06-27 07:52:05 深夜i     --     --
C++ 字符串 去掉空格

在C++中,有时候需要对字符串进行处理,其中就可能会涉及到去掉字符串首位的空格。下面介绍几种方法以供参考。

1. 使用STL库函数

C++标准库中的STL(Standard Template Library)提供了很多字符串处理函数。其中,string类的成员函数find_first_not_of()和find_last_not_of()可以用来查找字符串中第一个不属于指定字符集的字符的位置。通过这两个函数的返回值,就可以得到去掉首尾空格后的字符串。代码示例如下:


#include<iostream>

#include<string>

using namespace std;

int main()

{

  string str = "  hello world!  ";

  string::size_type pos = str.find_first_not_of(' ');

  str.erase(0, pos);

  pos = str.find_last_not_of(' ');

  if (pos != string::npos)

    str.erase(pos + 1);

  cout << str << endl;

  return 0;

}

输出结果为:


hello world!

2. 手动遍历字符串

如果不想使用STL库,可以手动遍历字符串,找到首尾非空格字符的位置,然后截取这个子串。代码示例如下:


#include<iostream>

#include<string>

using namespace std;

int main()

{

  string str = "  hello world!  ";

  int begin = 0, end = str.size() - 1;

  while (begin <= end && str[begin] == ' ')

    begin++;

  while (end >= begin && str[end] == ' ')

    end--;

  str = str.substr(begin, end - begin + 1);

  cout << str << endl;

  return 0;

}

输出结果为:


hello world!

3. 使用正则表达式

C++11标准引入了regex库,可以使用正则表达式对字符串进行处理。具体做法是使用regex_replace()函数,将首尾的空格替换为一个空字符串。代码示例如下:


#include<iostream>

#include<string>

#include<regex>

using namespace std;

int main()

{

  string str = "  hello world!  ";

  str = regex_replace(str, regex("^\\s+|\\s+$"), "");

  cout << str << endl;

  return 0;

}

输出结果为:


hello world!

总之,在C++中去掉字符串首位的空格,有多种方法可供选择。根据具体情况选择一种最适合的方法即可。

  
  

评论区

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