在C中解析整数和字符的数组

时间:2015-01-10 18:23:15

标签: c arrays parsing

我有两个这样的阵列:

char test_results[] = "20 7 1 12 3"
int  test[]         = {3, 8, 9, 12, 6}

我想逐个采用test_results的数字,并将其与test数组的数字进行比较。如果有任何巧合,请打印结果。

我该怎么做?谢谢!

1 个答案:

答案 0 :(得分:-1)

这应该是你需要的

char  text[] = "20 7 1 12 3";
int   test[] = {3, 8, 9, 12, 6};
char *ptr;
int   count;

ptr   = text;
count = sizeof(test) / sizeof(*test);
while (*ptr != '\0')
{
    int value;
    int i;

    value = strtol(ptr, &ptr, 10);
    for (i = 0 ; i < count ; i++)
    {
        if (value == test[i])
            printf("there is a coincidence at the %dth number of the array %d\n", i, value);
    }
}

将输出

  

there is a coincidence with the 3th number of the array 12
  there is a coincidence with the 0th number of the array 3