【问题标题】:Remove trailing 0s and decimal if necessary from string如有必要,从字符串中删除尾随的 0 和小数
【发布时间】:2023-03-15 00:50:01
【问题描述】:

我正在尝试从小数中删除尾随零,如果没有更多尾随零,则删除小数。

这个字符串是从 boost 的 gmp_float 字符串输出中产生的。

这是我的尝试,但我收到了std::out_of_range:

string trim_decimal( string toFormat ){
    while( toFormat.find(".") && toFormat.substr( toFormat.length() - 1, 1) == "0" || toFormat.substr( toFormat.length() - 1, 1) == "." ){
        toFormat.pop_back();
    }
    return toFormat;
}

如果存在小数点,如何删除尾随 0s,如果小数点后没有更多 0s,如何删除小数点?

【问题讨论】:

    标签: c++ string zero decimal-point trailing


    【解决方案1】:

    您需要将其更改为:

    while( toFormat.find(".")!=string::npos   // !=string::npos is important!!!
        && toFormat.substr( toFormat.length() - 1, 1) == "0" 
        || toFormat.substr( toFormat.length() - 1, 1) == "." )
    {
        toFormat.pop_back();
    }
    

    这里的关键是添加!=string::npos。找不到时,std::basic_string::find() 将返回 std::basic_string::npos,它不等于 false(不是您所期望的)。

    static const size_type npos = -1;
    

    【讨论】:

      【解决方案2】:
          auto lastNotZeroPosition = stringValue.find_last_not_of('0');
          if (lastNotZeroPosition != std::string::npos && lastNotZeroPosition + 1 < stringValue.size())
          {
              //We leave 123 from 123.0000 or 123.3 from 123.300
              if (stringValue.at(lastNotZeroPosition) == '.')
              {
                  --lastNotZeroPosition;
              }
              stringValue.erase(lastNotZeroPosition + 1, std::string::npos);
          }
      

      在 C++ 中你有 std::string::find_last_not_of

      【讨论】:

        猜你喜欢
        • 2012-11-03
        • 2021-09-22
        • 2018-06-05
        • 2011-10-04
        • 1970-01-01
        • 2015-04-03
        • 1970-01-01
        • 2011-08-12
        相关资源
        最近更新 更多