Search code examples
cfor-loopc-stringsstrcmp

Check whether a given substring is present in the given string


I should write a program in C to check whether a given substring is present in the given string. The code I wrote is below but it doesn't work. Can anyone tell me where the problem is?

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

int main(void)
{
   char str[30]="the test string";
   char sbstr[30]="test";
   char strcp[30];
   int len = strlen(str);
   int i=0;
   int p=0;

   while(i<len)
   {
       while (str[i] != '\0' && str[i] != ' ')
       {
             strcp[i] = str[i];
              ++i;
       }
       strcp[i] = '\0';

       p = strcmp(sbstr, strcp);

       if (p==0)
       {
           printf("exist");
           break;
       }

       ++i;
   }

}

Solution

  • I know you've already accepted an answer, but here's a slightly more efficient way to do a substring comparison that does not involve making a copy of the candidate substring to begin with in each iteration.

    char str[30]="the test string";
    char sbstr[30]="test";
    int len = strlen(str);
    int sublen = strlen(sbstr);
    int found = 0;
    int i = 0;  // starting index in str to start comparing on
    
    while (!found && sublen <= len) {
        found = 1;
    
        // found = !strncmp(str+i, sbstr, sublen);
        for (int j = 0; j < sublen; j++) {
            if (str[i+j] != sbstr[j]) {
               found = 0;
               break;
            }    
        }
    
        if (!found) {
            i++;
            len--;
        }
    }
    
    if (found) {
        printf("Exists starting at index %d\n", i);
    }
    

    And if you really want to get hardcore, there are well known algorithms such as the Boyer–Moore string-search algorithm which can search faster by using a table-lookup scheme IIRC.