从字符串 C++ 的末尾删除空格字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6057245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:24:57  来源:igfitidea点击:

Remove space chars from end of string C++

c++string

提问by maffo

Possible Duplicate:
What's the best way to trim std::string

可能的重复:
修剪 std::string 的最佳方法是什么

I have a string:

我有一个字符串:

std::string foo = "This is a string    "; // 4 spaces at end

How would I remove the spaces at the end of the string so that it is:

我将如何删除字符串末尾的空格,以便它是:

"This is a string" // no spaces at end

please note this is an example and not a representation of my code. I do not want to hard code:

请注意,这是一个示例,而不是我的代码的表示。我不想硬编码:

std::string foo = "This is a string"; //wrong

采纳答案by Vladimir Ivanov

Hereyou can find a lot of ways to trim the string.

在这里你可以找到很多修剪字符串的方法。

回答by NPE

First off, NULL chars (ASCII code 0) and whitespaces (ASCII code 32) and not the same thing.

首先,NULL 字符(ASCII 代码 0)和空格(ASCII 代码 32)不是一回事。

You could use std::string::find_last_not_ofto find the last non-whitespace character, and then use std::string::resizeto chop off everything that comes after it.

您可以使用std::string::find_last_not_of找到最后一个非空白字符,然后使用它std::string::resize来砍掉后面的所有内容。

回答by Peteris

string remove_spaces(const string &s)
{
  int last = s.size() - 1;
  while (last >= 0 && s[last] == ' ')
    --last;
  return s.substr(0, last + 1);
}