I wrote this code to find if string s2 is a substring of string s1. However I'm getting time limit exceeded. How can I make my algorithm better?

#include<stdio.h>

 int main()
{
char s1[20], s2[20];

scanf("%s %s", s1,s2);


char *p, *q, *count;
p=s1;
q=s2;
int i=21;

do{

   if(*p==*q)                 /* the strings are compared */
   {
   count=p;
    while(*p==*q)
        {(*p)++; (*q)++;}

    if(*q=='\0')
   {
    i=0;
      while(&s1[i]!= count)         /* count =p to get the index where the substring match starts */
      i++;
      printf("%d",i);
      break;
    }
    else
    { q=s2; (*p)--;}
  }     
 }
while((++(*p))!='\0');

if(i==21)                    /* if s2 is not a substring print -1 */
printf("-1");

 return 0;  
}

At lines 21 and 35 you have used this construct (*a)++ where a is a char*. Think about what this does ...

Because of the * in (*a)++ you do not increament the pointer a but rather what it points to, a char. You almost certain meant to increment the pointer like this a++. Because of this as soon as the condition at line 20 is true, lines 20-21 form an infinite loop because if x == y then (x+1) == (y+1).

thanks Banfa

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.