We have two strings.
Word1
Word2
On top of the source file you should put the following which is used in some functions
1 | #define LETTERS 256 //256 ascii codes |
The first question requires a function that prints the common characters between these two strings. Here is a very easy way to do it, although not the most efficient.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | void common(char *word1,char *word2){ char ascii[LETTERS]={}; int i; // put the value 1 into the characters word1 has while(*word1!='\0'){ ascii[(int)*word1]=1; word1++; } //checks if the letters of word2 were in word1 too. //If their ascii value is 1 they were so they are printed while(*word2!='\0'){ if(ascii[(int)*word2]==1){ putchar(*word2); ascii[(int)*word2]=0; //we make the ascii code 0 again in order not to print it 2nd time } word2++; } putchar('\n'); } |
Part b, requires a function that erases all characters that are in word2 from word1. We have 2 solutions for this:
Solution 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | void erase(char *word1,char *word2){ char *t=word1,*p=word2,*j; while(*word1!='\0'){ while(*word2!='\0'){ if(*word1==*word2){ j=word1; while(*j!='\0'){ *j=*(j+1); j++; } word1--; break; } word2++; } word2=p; word1++; } printf("\nWord1: %s\n",t); } |
Solution 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | void erase2(char *word1,char *word2){ char ascii[LETTERS]={}; char *t,*p=word1; while(*word2!='\0'){ ascii[(int)*word2]=1; word2++; } while(*word1!='\0'){ if(ascii[(int)*word1]==1){ t=word1; while(*t!='\0'){ *t=*(t+1); t++; } }else word1++; } printf("\nWord1: %s\n",p); } |
and finally part c, requires a function that search inside word1 to find word2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | int word2_in_word1(char *word2,char *word1){ int length1=0,length2=0; int found=0,i,pos=0; char *t1=word1,*t2=word2; //get the size of each string while(*t1++) length1++; while(*t2++) length2++; //if word1 is less chars tha word2 then there is now way word2 is in word1 if(length2>length1) return 0; //one position at a time from word1 searching for word2 while(*word1!='\0'){ i=0; pos++; while(*(word2+i)!='\0'){ if(*(word1+i)==*(word2+i)){ i++; found=1; }else{ found=0; break; } } if(found==1) return pos; //we decrease the length of word1 cause now we moved to the next position //so we must again if word2 is bigger than the remaining word1 length1--; if(length2>length1) return 0; //move on to the next position in word1 word1++; } } |
