CDT CDT - 1 month ago 12
C Question

How to extract numbers from string in c?

Say I have a string like

ab234cid*(s349*(20kd
and I want to extract all the numbers
234, 349, 20
, what should I do ?

Answer

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if (isdigit(*p)) { // Upon finding a digit, ...
        long val = strtol(p, &p, 10); // Read a number, ...
        printf("%ld\n", val); // and print it.
    } else { // Otherwise, move on to the next character.
        p++;
    }
}

Link to ideone.