C++ Extract number from the middle of a string

后端 未结 8 762
南方客
南方客 2020-12-03 07:27

I have a vector containing strings that follow the format of text_number-number

Eg: Example_45-3

8条回答
  •  鱼传尺愫
    2020-12-03 07:33

    You can also use the built in find_first_of and find_first_not_of to find the first "numberstring" in any string.

        std::string first_numberstring(std::string const & str)
        {
          char const* digits = "0123456789";
          std::size_t const n = str.find_first_of(digits);
          if (n != std::string::npos)
          {
            std::size_t const m = str.find_first_not_of(digits, n);
            return str.substr(n, m != std::string::npos ? m-n : m);
          }
          return std::string();
        }
    

提交回复
热议问题