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

时间:2011-05-19 10:30:47

标签: c++ string

  

可能重复:
  What's the best way to trim std::string

我有一个字符串:

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

如何删除字符串末尾的空格,使其为:

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

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

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

3 个答案:

答案 0 :(得分:2)

Here你可以找到许多修剪字符串的方法。

答案 1 :(得分:1)

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

您可以使用std::string::find_last_not_of查找最后一个非空白字符,然后使用std::string::resize来删除之后的所有内容。

答案 2 :(得分:0)

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