Return to Snippet

Revision: 20043
at November 5, 2009 05:47 by Menda


Initial Code
/**
 * Return a string with all occurrences of substring sub replaced by rep.
 * @param str The original string
 * @param sub The substring to be replace
 * @param rep The replacement
 * @return The new string
*/
char *replace_str(char *str, char *sub, char *rep)
{
  static char buffer[4096];
  char *p;

  if(! (p = strstr(str, orig)))  // Is 'orig' even in 'str'?
    return str;

  strncpy(buffer, str, p - str); // Copy characters from 'str' start to 'orig' st$
  buffer[p - str] = '\0';

  sprintf(buffer + (p - str), "%s%s", rep, p + strlen(orig));

  return buffer;
}

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

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

Initial Title
Replace substring with other string

Initial Tags
replace, c

Initial Language
C