By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,820 Members | 1,189 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,820 IT Pros & Developers. It's quick & easy.

replace a word in a line C language

100+
P: 254
i was wondering how to replace a word in a line.

i search in google.com and thescipts.com, i hardly to find what i want.

for example this line,

"I like his daughter"

replace his with "her".

first, i find the substring "him" in the line.
and then replae it with "her" at that position(string address), to let it become,

"I like her daughter"

how am i do that in C language ?
any idea?

i dont give the code here cos what i want is just the code of replacing the word baisically, that i dont know what to code.
-----------
thanks.
Mar 11 '07 #1
Share this Question
Share on Google+
3 Replies


100+
P: 1,646
First check out this function for finding a string in text and then lookup 'replace' in your c help
Mar 11 '07 #2

100+
P: 553
This might be non-professional but a working example of how this could be implemented with comments :

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<string.h>
  3.  
  4.  
  5. void main()
  6. {
  7.  
  8.     char str[20] = "this is big house";
  9.  
  10.     char *wordtoDelete = "big";
  11.     char *replaceWith= "small";
  12.  
  13.     char *temp= "";
  14.  
  15. temp = strstr(str,wordtoDelete);    // got at start of 'word to replace' word
  16.  
  17. //get all which is after the 'word to replce'
  18. char *getafter = temp + strlen(wordtoDelete); 
  19.  
  20. int pos = temp-str;  // start of 'word to delete' position
  21.  
  22. //end the string before the 'word to replace word'
  23. str[pos] = '\0';
  24.  
  25. char newS[50];
  26. strcpy(newS,str);  //copy the string before the 'word to delete'
  27.  
  28. strcat(newS,replaceWith);       //append the word you want to replace
  29.  
  30. strcat(newS,getafter);       // append all which was after the 'word to delete'
  31. puts(newS);
  32.  
  33.  
  34. }
Let me know how you find it.
Mar 11 '07 #3

Banfa
Expert Mod 5K+
P: 8,916
First check out this function for finding a string in text and then lookup 'replace' in your c help
An interesting function that can not possibly work as advertised without introducing undefined behaviour. It mallocs 1 character too few for the buffer it copies to in order to compare against resulting (I guess) in a buffer over-run when it calls Left (either that or it fails to zero terminate the string.

Additionally it is woefully in efficient compared to what could be written in straight C/C++ ignoring trying to make it VB like, which should not need to copy any memory.
Mar 12 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.