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.
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)