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
a fix to fann95's response, using in-place modification of the string, and assuming the buffer pointed to by line is large enough to hold the resulting string.
Here is the one that I created based on these requirements:
Replace the pattern regardless of whether is was long or shorter.
Not use any malloc (explicit or implicit) to intrinsically avoid memory leaks.
Replace any number of occurrences of pattern.
Tolerate the replace string having a substring equal to the search string.
Does not have to check that the Line array is sufficient in size to hold the replacement. e.g. This does not work unless the caller knows that line is of sufficient size to hold the new string.
Any suggestions for improving this code are cheerfully accepted. Just post the comment and I will test it.
You can use this function (the comments explain how it works):
This is possibly the best you could do:
a
andb
char*
if you don't want in-place modification, or you have to work with a
const char*
, this is another version of the same function that returns a new char* with modifications done. (don't forget tofree
the return value asstrdup()
is doing amalloc
behind the scene)Sample code :
Output: