有一个带有一行文本的字符串。比方说:
char * line = "Foo|bar|Baz|23|25|27";
我必须找到数字。
我在想这样的事情:
- 如果给定的 char 是一个数字,让我们把它放到一个临时的 char 数组中。(缓冲)
- 如果下一个字符不是数字,让我们将缓冲区设为一个新的 int。
问题是......我如何在这样的字符串中找到数字?
(我对 C99/gcc 不太熟悉。)
使用的编译器:gcc 4.3(环境是Debian Linux stable。)
我将采用以下方法:
一些可能有用的库函数是strtok
, isdigit
, atoi
.
#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