How to extract numbers from string in c?

后端 未结 7 866
终归单人心
终归单人心 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:14

    A possible solution using sscanf() and scan sets:

    const char* s = "ab234cid*(s349*(20kd";
    int i1, i2, i3;
    if (3 == sscanf(s,
                    "%*[^0123456789]%d%*[^0123456789]%d%*[^0123456789]%d",
                    &i1,
                    &i2,
                    &i3))
    {
        printf("%d %d %d\n", i1, i2, i3);
    }
    

    where %*[^0123456789] means ignore input until a digit is found. See demo at http://ideone.com/2hB4UW .

    Or, if the number of numbers is unknown you can use %n specifier to record the last position read in the buffer:

    const char* s = "ab234cid*(s349*(20kd";
    int total_n = 0;
    int n;
    int i;
    while (1 == sscanf(s + total_n, "%*[^0123456789]%d%n", &i, &n))
    {
        total_n += n;
        printf("%d\n", i);
    }
    

提交回复
热议问题