C++ Extract number from the middle of a string

2019-01-18 09:12发布

I have a vector containing strings that follow the format of text_number-number

Eg: Example_45-3

I only want the first number (45 in the example) and nothing else which I am able to do with my current code:

std::vector<std::string> imgNumStrVec;
for(size_t i = 0; i < StrVec.size(); i++){
    std::vector<std::string> seglist;
    std::stringstream ss(StrVec[i]);
    std::string seg, seg2;
    while(std::getline(ss, seg, '_')) seglist.push_back(seg);
    std::stringstream ss2(seglist[1]);
    std::getline(ss2, seg2, '-');
    imgNumStrVec.push_back(seg2); 
}

Are there more streamlined and simpler ways of doing this? and if so what are they?

I ask purely out of desire to learn how to code better as at the end of the day, the code above does successfully extract just the first number, but it seems long winded and round-about.

8条回答
混吃等死
2楼-- · 2019-01-18 10:02

Check this out

std::string ex = "Example_45-3";
int num;
sscanf( ex.c_str(), "%*[^_]_%d", &num );
查看更多
该账号已被封号
3楼-- · 2019-01-18 10:05
std::string s = "Example_45-3";
int p1 = s.find("_");
int p2 = s.find("-");
std::string number = s.substr(p1 + 1, p2 - p1 - 1)
查看更多
登录 后发表回答