Home > Software design >  Check whether a given substring is present in the given string
Check whether a given substring is present in the given string

Time:12-24

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

}

CodePudding user response:

For the array strcp

char strcp[30]; 

you need to support a separate index.

Something like

   int j = 0;
   while (str[i] != '\0' && str[i] != ' ')
   {
         strcp[j  ] = str[i  ];
   }
   strcp[j] = '\0';

Pay attention to that there is standard C function strstr that can be used to perform the task.

CodePudding user response:

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.

CodePudding user response:

its going to compare the whole string, thats why buddy.

  • Related