/ Published in: C
The original string (str) will be changed after calling this function, so if you need it make a copy of it.
Expand |
Embed | Plain Text
/** * 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; }
Comments
Subscribe to comments
- Posted By: evanmeng on April 22, 2010
- 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.
- This function only replaces the first occurrence of the sub-string, not all occurrences.
- The original string (str) is NOT changed after calling this function.
- What if the replaced string contains more than 4096 characters?
You need to login to post a comment.
