Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract digit(s) from the end of string

Tags:

c++

c

stl

Given strings like the following:

   sdfsd34 
    sdfdsf1

I would like to extract: 34, 1 using c++ (STL but no boost), c.

thanks

like image 448
vehomzzz Avatar asked Nov 01 '10 19:11

vehomzzz


2 Answers

You’re searching for the function string.find_last_not_of:

string str = "sdfsd34";
size_t last_index = str.find_last_not_of("0123456789");
string result = str.substr(last_index + 1);
like image 195
Konrad Rudolph Avatar answered Sep 20 '22 13:09

Konrad Rudolph


A lot here depends on whether you're more comfortable with string manipulation, or with STL-style iterators and such. As @Konrad already pointed out, std::string has find_last_not_of built in, for anybody who likes string-style manipulation.

If you prefer, you can work with a string a bit more like a container, and find the first non-digit starting from the end:

std::string::iterator pos = std::find_if(
    mystring.rbegin(), 
    mystring.rend(), 
    std::not1(std::isdigit)).base();

In this case, the conversion from reverse_iterator to iterator happens to work out very nicely. The reverse_iterator returned by find_if will refer to the last element before a contiguous set of digits at the end of the string. The base of that, however, will refer to the first of the digits (or mystring.end() if there are no digits at the end or (unfortunately) if the whole string consists of digits).

like image 41
Jerry Coffin Avatar answered Sep 22 '22 13:09

Jerry Coffin