Search code examples
cpointer-arithmeticstrstr

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 (if any). 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 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;
}

Solution

  • Since digits are not consecutive, and it contains '_' too, you need a way to scan them and skip scanning if its neither a digit nor a '_'

    Something like this :

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

    See HERE