replace a word in a line C language

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nickyeng
    Contributor
    • Nov 2006
    • 252

    replace a word in a line C language

    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.
  • willakawill
    Top Contributor
    • Oct 2006
    • 1646

    #2
    First check out this function for finding a string in text and then lookup 'replace' in your c help

    Comment

    • questionit
      Contributor
      • Feb 2007
      • 553

      #3
      This might be non-professional but a working example of how this could be implemented with comments :

      Code:
      #include<stdio.h>
      #include<string.h>
      
      
      void main()
      {
      
      	char str[20] = "this is big house";
      	
      	char *wordtoDelete = "big";
      	char *replaceWith= "small";
      
      	char *temp= "";
      
      temp = strstr(str,wordtoDelete);    // got at start of 'word to replace' word
      
      //get all which is after the 'word to replce'
      char *getafter = temp + strlen(wordtoDelete); 
      
      int pos = temp-str;  // start of 'word to delete' position
      
      //end the string before the 'word to replace word'
      str[pos] = '\0';
      
      char newS[50];
      strcpy(newS,str);  //copy the string before the 'word to delete'
      
      strcat(newS,replaceWith);       //append the word you want to replace
      
      strcat(newS,getafter);       // append all which was after the 'word to delete'
      puts(newS);
      
      
      }
      Let me know how you find it.
      Last edited by Ganon11; Mar 11 '07, 10:20 PM. Reason: code tags added

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Originally posted by willakawill
        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.

        Comment

        Working...