Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading