Removing duplicate words from a string

Code
  1. int main()

  2. {

  3.         char arr[1000];

  4.         char *temp=NULL;

  5.         char *temp1=malloc(100);

  6.         int len;

  7.         printf("enter the string:

  8. ");

  9.         gets(arr);

  10.         len=strlen(arr);

  11.         puts(arr);

  12.         printf("len:%d

  13. ",len);

  14.         temp=strtok(arr," ");

  15.        

  16.         if(temp!=NULL)

  17.                 strcpy(temp1,temp);

  18.        

  19.         while(temp!=NULL)

  20.         {

  21.                

  22.                 temp=strtok(NULL," ");

  23.                

  24.                 if(strstr(temp1,temp)==NULL)

  25.                 {

  26.                        

  27.                         strcat(temp1," ");

  28.                         strcat(temp1,temp);

  29.                        

  30.                 }

  31.         }

  32.         strcpy(arr,temp1);

  33.         printf("arr:%s",arr);

  34.         return 0;

  35. }

  36.  
Copyright GeekInterview.com


This is giving me runtime error why ?

Questions by pro_learner

Showing Answers 1 - 9 of 9 Answers

You need to check that temp isnt null after the call to strtok() in the loop. See the attachment for a fix.

Code
  1. temp = strtok(NULL, " ");

  2.  

  3. if (temp != NULL && strstr(temp1,temp) == NULL)

  Was this answer useful?  Yes

mangesh

  • Feb 18th, 2015
 

How can we failed procedure in normal plsql code.

  Was this answer useful?  Yes

Vipul Behl

  • Oct 3rd, 2015
 

There is an easier way to do this, you can easily do this by using string functions strtok and strstr. See the code.

Code
  1. #include<stdio.h>

  2. #include<string.h>

  3. int main()

  4. {

  5.         char s1[100],s2[100];

  6.         char *token,*c;

  7.         printf("Enter the first string : ");

  8.         gets(s1);

  9.         printf("Enter the second string : ");

  10.         gets(s2);

  11.        

  12.         token=strtok(s1," ");

  13.         while(token!=NULL)

  14.         {

  15.                 c=strstr(s2,token);

  16.                 if(c)

  17.                 {

  18.                         printf("%s

  19. ",token);

  20.                 }

  21.                 token=strtok(NULL," ");

  22.         }

  23.         return 0;

  24. }

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions