Given a (char *) string, I want to find all occurrence of a substring and replace it with an alternate string. I do not see any simple function that achieves this in <string.h>
相关问题
- Multiple sockets for clients to connect to
- how to split a list into a given number of sub-lis
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Generate string from integer with arbitrary base i
The optimizer should eliminate most of the local variables. The tmp pointer is there to make sure strcpy doesn't have to walk the string to find the null. tmp points to the end of result after each call. (See Shlemiel the painter's algorithm for why strcpy can be annoying.)
The repl_str() function on creativeandcritical.net is fast and reliable. Also included on that page is a wide string variant, repl_wcs(), which can be used with Unicode strings including those encoded in UTF-8, through helper functions - demo code is linked from the page. Belated full disclosure: I am the author of that page and the functions on it.
There isn't one.
You'd need to roll your own using something like strstr and strcat or strcpy.
i find most of the proposed functions hard to understand - so i came up with this:
output must be free'd
There you go....this is the function to replace every occurance of
char x
withchar y
within character stringstr
An example usage could be
The function is from a string library I maintain on Github, you are more than welcome to have a look at other available functions or even contribute to the code :)
https://github.com/fnoyanisi/zString
EDIT: @siride is right, the function above replaces chars only. Just wrote this one, which replaces character strings.
And below is the output
You could build your own replace function using strstr to find the substrings and strncpy to copy in parts to a new buffer.
Unless what you want to
replace_with
is the same length as what you you want toreplace
, then it's probably best to use a new buffer to copy the new string to.