如何从c中的字符串中提取数字?

CDT*_*CDT 15 c string

假设我有一个字符串ab234cid*(s349*(20kd,我想提取所有数字234, 349, 20,我该怎么办?

das*_*ght 24

你可以这样做strtol,像这样:

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++;
    }
}
Run Code Online (Sandbox Code Playgroud)

链接到ideone.

  • 怎么样,如果它有负数,比如ab-234cid*?? (5认同)
  • @HappyGreenKidNaps这就是使`strtol`的第二个参数如此有用的原因. (2认同)

hmj*_*mjd 13

使用sscanf()和扫描集的可能解决方案:

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);
}
Run Code Online (Sandbox Code Playgroud)

where %*[^0123456789]表示忽略输入,直到找到一个数字.请参阅http://ideone.com/2hB4UW上的演示.

或者,如果数字的数量未知,您可以使用%n说明符记录缓冲区中读取的最后位置:

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);
}
Run Code Online (Sandbox Code Playgroud)