Friday, October 30, 2009

Chap9[F]a Replacing words in sentences

Write a program that uses an array of pointers to strings str[ ]. Receive two strings str1 and str2 and check if str1 is embedded in any of the strings in str[ ]. If str1 is found, then replace it with str2.

char *str[ ] = { "We will teach you how to...",
"Move a mountain",
"Level a building",
"Erase the past",
"Make a million",
"...all through C!"
} ;

For example if str1 contains "mountain" and str2 contains "car", then the second string in str should get changed to "Move a car".





















Note: There is a limitation to this code
*** Except for the first sentence if the word you want to replace is longer than the original word the program doesn't work ideally.
So the replace function seem in the program works only on single line sentences(i.e One dimension char array).

The reason for this is that a longer word pushes the location of the last letter of the sentence into the next sentence.For example if a is replace with two in the mountain sentence then the last letter "n" of mountain gets pushed to a location at around "e" in "Level" in the next sentence. The code in replace only accounts for longer words in one sentence.

If you want to overcome this limitation then add a new string array.
"replace" function becomes replace(char *m,int j,char *n,char *new) where char *new is a blank array defined in main(). Then pass this blank array to char *new in replace function.

No comments:

Post a Comment