Replace substring with other string


/ Published in: C
Save to your folder(s)

The original string (str) will be changed after calling this function, so if you need it make a copy of it.


Copy this code and paste it in your HTML
  1. /**
  2.  * Return a string with all occurrences of substring sub replaced by rep.
  3.  * @param str The original string
  4.  * @param sub The substring to be replace
  5.  * @param rep The replacement
  6.  * @return The new string
  7. */
  8. char *replace_str(char *str, char *sub, char *rep)
  9. {
  10. static char buffer[4096];
  11. char *p;
  12.  
  13. if(! (p = strstr(str, orig))) // Is 'orig' even in 'str'?
  14. return str;
  15.  
  16. strncpy(buffer, str, p - str); // Copy characters from 'str' start to 'orig' st$
  17. buffer[p - str] = '\0';
  18.  
  19. sprintf(buffer + (p - str), "%s%s", rep, p + strlen(orig));
  20.  
  21. return buffer;
  22. }

URL: http://www.linuxquestions.org/questions/programming-9/replace-a-substring-with-another-string-in-c-170076/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.