How do you search a std::string for a substring in C++?

后端 未结 6 786
南方客
南方客 2020-12-10 16:34

I\'m trying to parse a simple string in C++. I know the string contains some text with a colon, followed immediately by a space, then a number. I\'d like to extract just t

6条回答
  •  不知归路
    2020-12-10 17:06

    I'm surprised that no one mentioned regular expressions. They were added as part of TR1 and are included in Boost as well. Here's the solution using regex's

    typedef std::tr1::match_results Results;
    
    std::tr1::regex re(":[[:space:]]+([[:digit:]]+)", std::tr1::regex::extended);
    std::string     str("Sectors: 4095");
    Results         res;
    
    if (std::tr1::regex_search(str, res, re)) {
        std::cout << "Number found: " << res[1] << std::endl;
    } else {
        std::cerr << "No number found." << std::endl;
    }
    

    It looks like a lot more work but you get more out of it IMHO.

提交回复
热议问题