Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

how to find the largest sequence in the given string.Can u find where i have gone wrong in the below code?

–2 votes
asked Jul 5, 2019 by Harika (160 points)
#include<stdio.h>

#include<string.h>

int main ()

{

  char str[100], sub[50], *p, temp[50];

  int i, len;

  setbuf (stdout, NULL);

  printf ("Give a Sequence:");

  gets (str);

  printf ("The Sequence u want:");

  gets (sub);

  len = strlen (sub);

  do

    {

      p = strstr (str, sub);

      if (p == '\0')

{

    len--;

  strncpy (temp,sub,len);

  strcpy (sub, temp);

}

    }

  while (p == '\0');

  printf ("The biggest sequence is:");

  puts (sub);

}

sample output:

Give a Sequence:dftfhglhjuhjh

The Sequence u want:hjhhh

The biggest sequence is:hjh

1 Answer

+1 vote
answered Aug 8, 2019 by Loki (1,600 points)
selected Aug 10, 2019 by Harika
 
Best answer
I have corrected the code:

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

int main ()
{
  char str[100], sub[50], *p;
  int i, len;
  setbuf(stdout, NULL);
  printf("Give a Sequence:");
  gets(str);
  printf("The Sequence u want:");
  gets(sub);
  len = strlen(sub);
  printf("len=%d",len);
  do
  {
      p = strstr (str, sub);
      if (p==0)
      {
          char temp[50]={0};     // declare and initialze in loop
          printf("sub=%s\n",sub);
          strncpy (temp,sub,--len);
          strcpy (sub, temp);
      }      
  }while(p==0);
  printf ("The biggest sequence is:");
  printf("%s",sub);
}

The temp[50] you are using must be cleared every time the loop runs and use p==0 instead of p=='\0' as it causes segmentation fault
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...