c - K&R Exercise Squeeze function -


this question has answer here:

so exercise here design program takes string , removes characters in string appear in second string. strings i've chosen below first string abc , second string cde want output of ab rather abc.

i've seen neat way squeeze function requires 2 simple loops wondering why long winded way doesn't work.

#include<stdio.h>  void squeeze(char s1[], char s2[]); void copy(char to[], char from[]);  int k=0;  main() {     char array1[4]="abc";     char array2[4]="cde";     squeeze(array1, array2);     printf("%s", array1); }  void squeeze(char s1[], char s2[]) {     int j,i,m;     m=j=i=0;     char s3[1000];     while(s1[i]!='\0')   //what i'm doing here taking character in string     {                      //and comparing characters in second string.         copy(s3,s1);       //if exists in second string i'm 'deleting' letter         while(s2[j]!='\0') //from first string. start on again         {                 // next letter in line. or @ least that's plan.             if (s1[i]==s2[j])             {                 k=1;             }             ++j;         }          if (k==1)         {             m=i;             while(s3[m+1]!='\0')             {                 s1[m]=s3[m+1];  //i'm 'deleting' letter pushing each character                 ++m;            //that right of deleted character               }                   //left of array.         }          if(k!=1)         {             ++i;         }     }     s1[i]='\0';  }  void copy(char to[], char from[]) {     int i;     i=0;      while(from[i]!='\0')     {         to[i]= from[i];         ++i;     }     to[i]=='\0'; } 

inside outer while should reset "j" zero.

if "k" bekomes 1, not increment "i" more. if run squeeze() second time, not initialize "k" again.

never use global variables (or module local variables) "k". makes code thread-unsafe.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -