How to extract numbers from string in c?

后端 未结 7 867
终归单人心
终归单人心 2020-11-29 04:55

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

7条回答
  •  盖世英雄少女心
    2020-11-29 05:22

    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) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
            // Found a number
            long val = strtol(p, &p, 10); // Read number
            printf("%ld\n", val); // and print it.
        } else {
            // Otherwise, move on to the next character.
            p++;
        }
    }
    

    Link to ideone.

提交回复
热议问题