-1

I'm trying to read numbers from a string e.g. if

string str = "1Hi15This10";

I want to get (1,15,10)

I tried by index but I read 10 as 1 and 0 not 10. I could not use getline because the string is not separated by anything.

Any ideas?

Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
  • This may help you: http://stackoverflow.com/questions/17331250/read-all-integers-from-string-c – Mo Abdul-Hameed Oct 07 '16 at 22:12
  • Are you familiar with matching by using a regular expression? You can use something like `/(\d+)/g` to match groups of integers in a string and then parse out the ints themselves in the strings returned as groups. – orphen Oct 07 '16 at 22:13

2 Answers2

1

without regex you can do this

std::string str = "1Hi15This10";
for (char *c = &str[0]; *c; ++c)
   if (!std::isdigit(*c) && *c != '-' && *c != '+') *c = ' ';

the integers are now seperated by a space delimiter which is trivial to parse

  • Can also use `!std::isdigit(*c)`, which would also cope with non-letters. Also might need to adapt the approach to allow for presence of sign characters (`+` or `-`). – Peter Oct 07 '16 at 22:41
  • This potentially invokes Undefined Behavior. [Details](https://stackoverflow.com/questions/21805674/do-i-need-to-cast-to-unsigned-char-before-calling-toupper) – Baum mit Augen Oct 07 '16 at 23:18
0

IMHO the best way would be to use a regular expression.

#include <iostream>
#include <iterator>
#include <string>
#include <regex>

int main() {
    std::string s = "1Hi15This10";

    std::regex number("(\\d+)");  // -- match any group of one or more digits

    auto begin = std::sregex_iterator(s.begin(), s.end(), number);

    // iterate over all valid matches  
    for (auto i = begin; i != std::sregex_iterator(); ++i) {
        std::cout << "  " << i->str() << '\n';
        // and additional processing, e.g. parse to int using std::stoi() etc.
    }
}

Output:

  1
  15
  10

Live example here on ideone.

Yes, you could just write your own loop for this, but:

  1. you will probably make some silly mistake somewhere,
  2. a regular expression can be adapted to serve many different search patterns; e.g. what if tmr you decide you want to support decimal/negative/floating point numbers; these cases and many others will be easily supported with a regex, probably not so much with your custom solution :)
paul-g
  • 3,797
  • 2
  • 21
  • 36