基於sscanf,在this answer中建議的方法的一種可能的實施方式。
#include <stdio.h>
#include <string.h>
void find_integers(const char* p) {
size_t s = strlen(p)+1;
char buf[s];
const char * p_end = p+s;
int n;
/* tokenize string */
for (; p < p_end && sscanf(p, "%[^|]%n", &buf, &n); p += (n+1))
{
int x;
/* try to parse an integer */
if (sscanf(buf, "%d", &x)) {
printf("got int :) %d\n", x);
}
else {
printf("got str :(%s\n", buf);
}
}
}
int main() {
const char * line = "Foo|bar|Baz|23|25|27";
find_integers(line);
}
輸出:
$ gcc test.c && ./a.out
got str :(Foo
got str :(bar
got str :(Baz
got int :) 23
got int :) 25
got int :) 27
「的strcmp」 能做到這一點,有一個開關。如果char等於一個數字,我們繼續。但我不確定這是否是最好的方法。 (有一個自己的,長的函數,只是爲了檢查一個字符是否是一個數字。)@squiguy - 我會在一秒鐘內寫一個簡短的例子。 – Shiki
看看isdigit()。 –
@RandyHoward - 有答案。非常感謝你。 – Shiki