【问题标题】:How to get substring after a whitespace?如何在空格后获取子字符串?
【发布时间】:2018-02-15 20:36:06
【问题描述】:

根据:C++ How to get substring after a character?

x.substr(x.find(":") + 1);

我怎样才能做同样的事情,但要使用空格?因为find() 会忽略空格。

【问题讨论】:

  • 你有什么尝试解决你的作业?
  • @Vettel: "find() 忽略空格" - 不,它没有。 x.substr(x.find(" ") + 1); 工作得很好。 x.find(' ') 也可以使用
  • find 成员函数确实忽略空格。
  • @MayankJain:“Stringstream 让您指定分隔符” - 不,它没有。您可能会想到 std::getline(),它有一个可选的分隔符,并且可以使用字符串流作为输入。
  • 你应该看看here

标签: c++ string substring


【解决方案1】:

如果您想要空白,则需要使用 find_if() 和调用 is::space() 的适当 lambda

auto pos = find_if(std::begin(x), std::end(x), [](unsigned char c){return std::isspace(c);});
pos++;
for(;pos!=x.end();pos++)
cout << *pos;

【讨论】:

  • 请澄清一下。还有哪个角色? Ascii whitespace 的值为 32
  • 那是字符空间。 ASCII 32。“空白”是其他几个字符,包括制表符。见isSpace()en.cppreference.com/w/cpp/string/byte/isspace的定义
  • 噢,谢谢,我明白了。
  • 谢谢,但它给了我 substr 函数中的“pos”错误:imgur.com/a/guuDP
  • pos 是string::iterator
猜你喜欢
  • 2021-11-25
  • 2013-01-15
  • 2016-05-03
  • 2022-12-29
  • 2015-03-25
  • 2017-05-06
  • 2017-11-24
  • 2012-09-16
相关资源
最近更新 更多