Saturday, 7 September 2013

How to extract occurrence of str + digits from string in C

How to extract occurrence of str + digits from string in C

I'm learning my way through pointer arithmetic and am trying to find the
first occurrence of a string in the haystack using strstr() and from there
extract any first set of numbers. So for example:
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
How can I achieve this? Thanks.
Here's what I started with, but not sure how to do proceed.
#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;
}

No comments:

Post a Comment