Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Extract number from the middle of a string

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.

like image 233
fakeaccount Avatar asked May 06 '15 10:05

fakeaccount


People also ask

How do I extract an integer from the string in C?

How to extract numbers from string in C? Simple answer: Use strtol() or strtof() functions alongwith isdigit() function.

How do you read numbers in a string?

You can use sscanf here if you know the number of items you expect in the string: char const *s = "10 22 45 67 89"; sscanf(s, "%d %d %d %d %d", numbers, numbers+1, numbers+2, numbers+3 numbers+4);


1 Answers

You can also use the built in find_first_of and find_first_not_of to find the first "numberstring" in any string.

    std::string first_numberstring(std::string const & str)     {       char const* digits = "0123456789";       std::size_t const n = str.find_first_of(digits);       if (n != std::string::npos)       {         std::size_t const m = str.find_first_not_of(digits, n);         return str.substr(n, m != std::string::npos ? m-n : m);       }       return std::string();     } 
like image 88
Pixelchemist Avatar answered Oct 05 '22 18:10

Pixelchemist