C++ Extract number from the middle of a string

后端 未结 8 716
南方客
南方客 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:52

    Check this out

    std::string ex = "Example_45-3";
    int num;
    sscanf( ex.c_str(), "%*[^_]_%d", &num );
    
    0 讨论(0)
  • 2020-12-03 07:58

    Using @Pixelchemist's answer and e.g. std::stoul:

    bool getFirstNumber(std::string const & a_str, unsigned long & a_outVal)
    {
        auto pos = a_str.find_first_of("0123456789");
    
        try
        {
            if (std::string::npos != pos)
            {
                a_outVal = std::stoul(a_str.substr(pos));
    
                return true;
            }
        }
        catch (...)
        {
            // handle conversion failure
            // ...
        }
    
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题