2

我正在通过指针算术学习我的方法,并试图使用在大海捞针中找到第一次出现的字符串,strstr()并从那里提取任何第一组数字(如果有的话)。例如:

Needle: SPAM
Input:  Sept 10 2012; undefined SPAM (uid AUIZ); 03_23_1 user FOO 2012_2
Output: SPAM 03_23_1

Needle: BAR
Input:  Oct 10 2012; variable BAR; 93_23_1; version BAZ
Output: BAR 93_23_1

Needle: FOO
Input:  Oct 10 2012; variable FOOBAZ; version BAR
Output: FOOBAZ

我怎样才能做到这一点?谢谢。

这是我开始的,但不知道如何继续。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main ()
{
    char *first,*second;
    const char *str = "Sept 10 2012; undefined SPAM (uid AUIZ); 03_23_1 user FOO 2012_2";
    char *find = "SPAM";

    first = strstr(str, find);
    if (first != NULL)
    {
        second = first;
        while(*second != '\0')
        {
            if (isdigit(second[0]))
            {
                break;
            }
            second++;
        }
    }

    return 0;
}
4

1 回答 1

1

由于数字不是连续的,并且它也包含'_',因此您需要一种方法来扫描它们并跳过扫描,如果它既不是数字也不是'_'

像这样的东西:

char res[15]={'\0'};
if (first != NULL)
{
    start = second = first;
    while(*second != '\0')
    {
        if (isdigit(*second))
        {
           start =second; // Store the start of the "thing"
           //Start another loop to check for the "thing"
           while(*second != '\0')
              if(*second=='_' || isdigit(*second) )
                 second++;
              else
                  break;  //Something else, exit now

            break;
        }
        second++;
        start++;  
    }
}

strncpy ( res, start, second-start ); //Store Result
res[second-start] = '\0'; 
printf("%s  %s\n",find,res);

这里

于 2013-09-07T21:05:41.123 回答