Given strings like the following:
sdfsd34
sdfdsf1
I would like to extract: 34, 1 using c++ (STL but no boost), c.
thanks
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);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With