C++ Extract number from the middle of a string

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

    The 'best' way to do this in C++11 and later is probably using regular expressions, which combine high expressiveness and high performance when the test is repeated often enough.

    The following code demonstrates the basics. You should #include for it to work.

    // The example inputs
    std::vector inputs {
        "Example_0-0", "Example_0-1", "Example_0-2", "Example_0-3", "Example_0-4",
        "Example_1-0", "Example_1-1", "Example_1-2", "Example_1-3", "Example_1-4"
    };
    
    // The regular expression. A lot of the cost is incurred when building the
    // std::regex object, but when it's reused a lot that cost is amortised.
    std::regex imgNumRegex { "^[^_]+_([[:digit:]]+)-([[:digit:]]+)$" };
    
    for (const auto &input: inputs){
        // This wil contain the match results. Parts of the regular expression
        // enclosed in parentheses will be stored here, so in this case: both numbers
        std::smatch matchResults;
    
        if (!std::regex_match(input, matchResults, imgNumRegex)) {
            // Handle failure to match
            abort();
        }
    
        // Note that the first match is in str(1). str(0) contains the whole string
        std::string theFirstNumber = matchResults.str(1);
        std::string theSecondNumber = matchResults.str(2);
    
        std::cout << "The input had numbers " << theFirstNumber;
        std::cout << " and " << theSecondNumber << std::endl;
    }
    

提交回复
热议问题