【问题标题】:Two at a time string algorithms?一次两个字符串算法?
【发布时间】:2013-03-19 19:42:42
【问题描述】:

有没有办法在单个命令中执行以下操作(以避免测试)

if (mystring.find_first_not_of("X") != std::string::npos) {
    mystring.erase(0, mystring.find_first_not_of("X"));
}

【问题讨论】:

  • 您可以将find_first_not_of 的结果存储在一个变量中。您仍然需要进行测试,但这将是一个超级便宜的恒定时间操作。
  • 你可能会捏造std::find 和一个比较器。编辑:就在我按下回车键...
  • 另外,我感觉这里有一个 XY 问题。您的代码删除了前导 '0' 字符。您是否尝试解析或缩短整数字符串?因为您很可能不必删除前导'0' 字符。
  • @zneak : 完全没有,我可以写“A”或“B”
  • @DrewDormann 但事实并非如此;它的意思是“删除前导0s,除非字符串只是0s”。

标签: c++ string algorithm


【解决方案1】:
mystring.erase(0, std::max(0, (std::make_signed<std::string::size_type>::type)
                           mystring.find_first_not_of('X')));

或者没有 C++11:

mystring.erase(0, std::max(0, (int)mystring.find_first_not_of('X')));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多