Connecting Tech Pros Worldwide Forums | Help | Site Map

Replace a substring with another substring using c

Newbie
 
Join Date: Oct 2008
Posts: 6
#1: Oct 7 '08
i want to replace a word in given string

e. g

string ---- He is a good man.

in above string i want to replace "good" word with "gentle" so finally

i want to print bellow string :-

He is a gentle man.

plz give c program code without using string function.

Lives Here
 
Join Date: Sep 2006
Posts: 12,070
#2: Oct 7 '08

re: Replace a substring with another substring using c


Please read the posting guidelines. We won't do your homework and spoon feed you with code. Read some tutorials, try the code and post if you have problems with your code.
Member
 
Join Date: Aug 2008
Posts: 121
#3: Oct 8 '08

re: Replace a substring with another substring using c


What did you did to give the answer in writing??

First, you searched the sentence to find the word.
Then, if you found the word, then when you were writing the sentence again instead of writing the word it is there you wrote the new word.
Expand|Select|Wrap|Line Numbers
  1. isFound = searchWord( sentence, word_to_be_replaced );
  2.  
  3. if ( isFound ){
  4.    // code to replace
  5. }
  6.  
In the "code to replace" you can do many things...
One algorithm that comes quickly in mind is:

Find how many characters there will be in the new sentence
Allocate space for the new sentence
Copy the old sentence to the new sentence up to the point of the word removed
Copy the new word in the new sentence
Copy to the new sentence the remaining of the old sentence (if any)

Hope i helped,
Tassos Souris
Newbie
 
Join Date: Oct 2008
Posts: 6
#4: Oct 10 '08

re: Replace a substring with another substring using c


sir
i have read your answer, but i want the complete c program if it is possible.

i have tryed more, but failed.

plz send me complete c program without use of string functions.

thank u

from
abc
Member
 
Join Date: Aug 2008
Posts: 121
#5: Oct 10 '08

re: Replace a substring with another substring using c


I think it is against the rules to post a complete answer..

Oh, by the way, my previous "algorithm" (god make that one!) is not correct.. is just there to make you think about the solution.. It is not correct because there might be multiple occurrences of one string in one sentence, so then you must do and other things... or just change it a little.. like that "every time the word is found in the sentence..".. smt like that..
Newbie
 
Join Date: Oct 2008
Posts: 6
#6: Oct 10 '08

re: Replace a substring with another substring using c


plz refer this message....................................
sir

i have tryed and also success in replacing word, but it is too long and i wand to reduce the size if it is possible. plz give me kind information if any correction is necessary. plz check my program as per bellow.

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<conio.h>
  3.  
  4. void main()
  5. {
  6.     char s1[23],s2[12],s4[30],s3[12];
  7.     int i,j,flag=0,k,m,n=0;
  8.     clrscr();
  9.     printf("enter sentence :-");
  10.     gets(s1);
  11.     printf("enter word which u wish to replace from above sentence:-");
  12.     gets(s2);
  13.     printf("enter new word which u wish to replace:-");
  14.     gets(s3);
  15.     j=0;
  16.     for(i=0;s1[i];i++)
  17.     {
  18.  
  19.         if(s1[i]==s2[j] && s1[i]!='\0' && s2[j]!='\0')
  20.         {
  21.               j++;
  22.               if(s2[j]=='\0')
  23.               {
  24.  
  25.             for(k=0;s3[k];k++)
  26.             {
  27.                 s4[n]=s3[k];
  28.                 n++;
  29.             }
  30.             s4[n]=' ';
  31.             flag=1;
  32.               }
  33.               continue;
  34.         }
  35.         else
  36.         {
  37.             if(flag==1)
  38.             {
  39.                 s4[n]=s1[i];
  40.                 n++;
  41.             }
  42.             if(flag==0)
  43.             {
  44.                 s4[n]=s1[i];
  45.                 n++;
  46.                 j=0;
  47.             }
  48.  
  49.  
  50.         }
  51.     }
  52.  
  53.     s4[n]='\0';
  54.     printf("s4=%s",s4);
  55.     getch();
  56. }
  57.  
thank u

from
abc
Member
 
Join Date: Aug 2008
Posts: 121
#7: Oct 10 '08

re: Replace a substring with another substring using c


Use code tags... no-one will read that code as you posted it...
boxfish's Avatar
Expert
 
Join Date: Mar 2008
Location: California
Posts: 478
#8: Oct 10 '08

re: Replace a substring with another substring using c


Yes. To use code tags, put [CODE] before the code and [/CODE] after it so it shows up in a box with a monospace font. At least on the browser I am using, IE7, not using code tags wrecks the indentation so the code is almost unreadable.
boxfish's Avatar
Expert
 
Join Date: Mar 2008
Location: California
Posts: 478
#9: Oct 10 '08

re: Replace a substring with another substring using c


There are a few things you can do to improve the code that you posted. For example:

I see no reason for the continue statement. If you're at the end of that first if statement, then you're just going to go to the top of the loop anyway, because the rest of the loop is consumed by the else that you won't be visiting.

On this line
if(s1[i]==s2[j] && s1[i]!='\0' && s2[j]!='\0')
I don't see a reason to check whether s1[i]!='\0' because the loop
for(i=0;s1[i];i++)
guarantees that s1[i]!='\0'.

And it would help a lot if you gave your variables more descriptive names. Instead of s1, s2, s3, and s4, call them things like oldPhrase, oldWord, newWord, and newPhrase. Instead of flag, call it something like findingWord. And make it boolean. And so on. And you can improve the code in the else statement.

main should return an int. On some compilers, code in which main does not return an int will not compile. It should return 0;

I think your professor will give you a lot more points if you put some comments in your code that explain how it works.

Hope this helps.
Member
 
Join Date: Aug 2008
Posts: 121
#10: Oct 10 '08

re: Replace a substring with another substring using c


Here are some tips:

- You have declared a variable called 'm' but you do not use it. This means that you have something wrong or you have forgot something, cause otherwise you wouldn't have included the 'm' variable.

-Supply more buffer for the sentences. Increase the size from 23 to let's say 50... Also, it is not a good idea to make the number of characters for the output array fixes because you do not know how many characters it will eventually have.. the word to replace one word from the sentence might be very big and even worse it might be replaced in many places.

- Change the numbers 23, 12, ... to #defines:
#define SENTENCE_MAX_LEN 50

-Change names s1, s2, s3... to for example:
char sentence[ SENTENCE_MAX_LEN ];

-Do not ever use gets()!!! Why? Because it does not check how many characters it receives and it might lead to memory leaks. Especially for your program, this is very easy. When you ask for a sentence, i just put a sentence. But most sentences are more than 22 characters... your program does not check this. If you are lucky you will get an assertion or something like that.
You must check the number of characters you receive to store them in the array. You use fgets() like this:
fgets( sentence, SENTENCE_MAX_LEN, stdin );
which says read up to one less than SENTENCE_MAX_LEN characters from stdin and store them in sentence. Also, put a '\0' character at the end.

Till that point your program can be restructured like that:
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. #define SENTENCE_MAX_LEN 50
  4. #define WORD_MAX_LEN 15
  5.  
  6. int main( void ){
  7.  
  8.    char sentence[ SENTENCE_MAX_LEN ];
  9.    char word[ WORD_MAX_LEN ];
  10.  
  11.     fprintf( stdout, "\nPlease enter one sentence. Note that i will accept only
  12.                                    %d characters!\n", SENTENCE_MAX_LEN - 1 );
  13.     fflush( stdout );
  14.     fgets( sentence, SENTENCE_MAX_LEN, stdin );
  15.     /* you might also want to get rid of unwanted-extra input here... */
  16.  
  17.     fprintf( stdout, "\nNow give me the word you want me to replace. Note that i
  18.                                    will accept only %d characters!\n", 
  19.                                    WORD_MAX_LEN - 1 );
  20.     fflush( stdout );
  21.     fgets( word, WORD_MAX_LEN, stdin );
  22.     /* you might also want to get rid of unwanted-extra input here... */
  23.  
  24.     ....
  25.  
  26.     return ( 0 );
  27.  
  28. }
  29.  
- Do not put everything in a big for loop. This is not the purpose of structural programming. Divide this thing in small routines that you can check, debug, modify and extend easily. What you must do is:
Find what does each section of your for loop accomplishes.
Make each task to a separate routine.


-Your for loop will execute meaninglessly even if the word in not found in the sentence. Check for that too.

To continue from above you can do:
Expand|Select|Wrap|Line Numbers
  1.      fprintf( stdout, "\nI am searching for the word \"%s\" you want me to   replace...\n", word );
  2.  
  3.      occurrences = searchWord( sentence, word );
  4.  
  5.     if ( occurences > 0 ){
  6.            fprintf( stdout, "\nI found the word %s %d times in the sentence.\n",
  7.                             word, occurrences );
  8.  
  9.            replaceWord( sentence, word );
  10.  
  11.     }
  12.     else{
  13.  
  14.       fprintf( stdout, "\nSorry but i did not found the word in the sentence... Goodbye!%c", '\n' );
  15.          return ( 1 );
  16.  
  17.     }
  18.  
-When you output, you say: s4=%s.
This is really, really bad. What the hell is s4??? How the hell will a user running the program know what s4 is? He does not know how you name your variables!!! Probably he does not know that behind the program there is source code!!!!!!!!!!!!
Make a friendly user interface. Put nice messages, like:
For input:
Type some text. I will only receive %d characters!
Please enter the word you want me to locale in the sentence and replace it with another word.
The word is not located in the sentence. Please enter again.
There are %d occurrences of the word in the sentence. Enter the word that you want to replace word %s.
For output:
The sentence with the word(s) replaced is: %s. ---> you do this like that:
Expand|Select|Wrap|Line Numbers
  1. fprintf( stdout, "\nThe sentence with the %s replaced is: %s\n", 
  2.                                                    occurrences == 1 ? "word" : "words", 
  3.                                                    newSentence );
  4.  
Personally, i suggest that you divide in its own routine even the part (in the code above i show you) that reads input. Assign the correct responsibilities to each of the routines.

Let us know how you progress!!
Newbie
 
Join Date: Oct 2008
Posts: 6
#11: Oct 11 '08

re: Replace a substring with another substring using c


sir,

a lots thank for kind guideline for good programing code and i also hope u will me give this type of tips always.

thanks again.....

sir i want to ask a question for bellow comments.....
i can't undestand it, plz explain with more detail..


and u suggest to check
On this line
if(s1[i]==s2[j] && s1[i]!='\0' && s2[j]!='\0')
I don't see a reason to check whether s1[i]!='\0' because the loop
for(i=0;s1[i];i++)
guarantees that s1[i]!='\0'.

thank

from
abc mavdi
Member
 
Join Date: Aug 2008
Posts: 121
#12: Oct 11 '08

re: Replace a substring with another substring using c


Quote:

Originally Posted by abcmavdi

sir,

a lots thank for kind guideline for good programing code and i also hope u will me give this type of tips always.

thanks again.....

sir i want to ask a question for bellow comments.....
i can't undestand it, plz explain with more detail..


and u suggest to check
On this line
if(s1[i]==s2[j] && s1[i]!='\0' && s2[j]!='\0')
I don't see a reason to check whether s1[i]!='\0' because the loop
for(i=0;s1[i];i++)
guarantees that s1[i]!='\0'.

thank

from
abc mavdi


your for loop
Expand|Select|Wrap|Line Numbers
  1. for ( i = 0; s1[ i ]; i++ ){
  2.   ...
  3. }
  4.  
does 3 things:
1. Set 0 to 'i'
2. Evaluate the expression s1[ i ].
3 If it is true execute the body of the for loop
4 At the end of the body of the for loop, execute i++
Repeat steps 2-4 until step 2 indicates false evaluation.

So, in simple words your for loop will continue executing until the expression:
Expand|Select|Wrap|Line Numbers
  1. s1[ i ];
  2.  
becomes false.

Well, s1[ i ] will hold a value.. it would be either a character (including spaces), or the terminating null character '\0'.
In the case of characters, evaluating the expression s1[ i ], means returning the character. The for loop then takes the character and sees if it is true or false. You should know that true means not-zero and false zero. Since, a character is nothing more than a small integer (you are working with ASCII characters, ranging from 0 to 255 i think), and it is greater than zero, then the value is true . So, for continues executing the body of the for loop.

When, however you reach the end of the array and encounter '\0', its value is zero. So, it is false and the for loop terminates.

Hope i helped!

With respect,
Tassos Souris
Newbie
 
Join Date: Oct 2008
Posts: 6
#13: Oct 11 '08

re: Replace a substring with another substring using c


sir

i have read ur.

but one problem is remaining which i explain in bellow :-

in a sentence like :- "i live in india"

word like :-"india"

replace word is:-"bharat"

then i will find output as per bellow :

output:-" lve bharat"

but i want to replace only "india" word whatever time it occurs in a sentence.

thanks

from
abc
Member
 
Join Date: Aug 2008
Posts: 121
#14: Oct 11 '08

re: Replace a substring with another substring using c


It seems that there is a serious problem in your code...
In Visual Studio 2008 sometimes it crashes, sometimes it continues execution with wrong results.... This means that you do something wrong..

What you must do is:
EXECUTE your code MENTALLY in a white paper... Write with a pencil all the variables and see how your code executes.. does it executes as you expect? If not, since you are keeping track of all the variables in the paper, you can figure out what goes wrong...

You can use tools to assist you. There seems to be a memory problem there.. with all these arrays.. you probably write past the boundaries of an array...
Use "Memory Profilers"... you can find many of them which are free (Open Source) for linux.. there are some for windows too...You can use a program called "lint" that checks C programs for common errors... You can use the debugger (get used to it!!!!!!!!!!!)......
You must learn how to use these tools... most importantly you must learn how to use these tools to find and solve bugs in your code.. like the one you are having now...

Do the above and let us know the results...
Reply