C++ Extract number from the middle of a string

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();
    }

Leave a Comment

tech