C++ Extract number from the middle of a string

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

    This should be more efficient than Ashot Khachatryan's solution. Note the use of '_' and '-' instead of "_" and "-". And also, the starting position of the search for '-'.

    inline std::string mid_num_str(const std::string& s) {
        std::string::size_type p  = s.find('_');
        std::string::size_type pp = s.find('-', p + 2); 
        return s.substr(p + 1, pp - p - 1);
    }
    

    If you need a number instead of a string, like what Alexandr Lapenkov's solution has done, you may also want to try the following:

    inline long mid_num(const std::string& s) {
        return std::strtol(&s[s.find('_') + 1], nullptr, 10);
    }
    

提交回复
热议问题