假设我有一个字符串ab234cid*(s349*(20kd
,我想提取其中所有的数字234, 349, 20
,应该怎么做?
你可以使用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++;
}
}
链接至ideone。
long long val = strtol();
?我宁愿使用 C99 的 strtoll()
或者将 val 定义为 long
:) - pmgstrtol
函数的第二个参数如此有用的原因。 - Sergey Kalinichenkostrto
函数族的示例都使用不同的变量作为结束指针。他们在调用后检查errno
,对返回值进行合理性检查以查看它是否在预期范围内,然后才覆盖字符串流的指针与结束指针。 - Happy Green Kid Napsp
的值将不会被调用更改(或者说,它将使用先前相同的值进行更新)。 - Stephen Canon使用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);
}
其中%*[^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);
}
234cid*(s349*(20kd
不起作用? - Sathyamoorthy R下面是一种使用sscanf
的简单解决方案:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str[256]="ab234cid*(s349*(20kd";
char tmp[256];
int main()
{
int x;
tmp[0]='\0';
while (sscanf(str,"%[^0123456789]%s",tmp,str)>1||sscanf(str,"%d%s",&x,str))
{
if (tmp[0]=='\0')
{
printf("%d\r\n",x);
}
tmp[0]='\0';
}
}
char tmp[256];
for(i=0;str[i];i++)
{
j=0;
while(str[i]>='0' && str[i]<='9')
{
tmp[j]=str[i];
i++;
j++;
}
tmp[j]=0;
printf("%ld", strtol(tmp, &tmp, 10));
// Or store in an integer array
}
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
void main(int argc,char *argv[])
{
char *str ="ab234cid*(s349*(20kd", *ptr = str;
while (*ptr) { // While there are more characters to process...
if ( isdigit(*ptr) ) {
// Found a number
int val = (int)strtol(ptr,&ptr, 10); // Read number
printf("%d\n", val); // and print it.
} else {
// Otherwise, move on to the next character.
ptr++;
}
}
}
或者你可以像这样编写一个简单的函数:
// Provided 'c' is only a numeric character
int parseInt (char c) {
return c - '0';
}
-123
算作数字吗?+123
呢? - Keith Thompson