Posted By

Menda on 11/05/09


replace String c substring

Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


Replace substring with other string

 / Published in: C


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

  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;
  13. if(! (p = strstr(str, orig))) // Is 'orig' even in 'str'?
  14. return str;
  16. strncpy(buffer, str, p - str); // Copy characters from 'str' start to 'orig' st$
  17. buffer[p - str] = '\0';
  19. sprintf(buffer + (p - str), "%s%s", rep, p + strlen(orig));
  21. return buffer;
  22. }

Report this snippet  


RSS Icon Subscribe to comments
Posted By: evanmeng on April 22, 2010
  1. This will not even compile! Because when you copy the code, you renamed the input parameter 'orig' to be 'sub', but not change accordingly in the function body.
  2. This function only replaces the first occurrence of the sub-string, not all occurrences.
  3. The original string (str) is NOT changed after calling this function.
  4. What if the replaced string contains more than 4096 characters?

You need to login to post a comment.