Re: Replacing a substring in a string [message #479994 is a reply to message #479987] |
Tue, 19 March 2013 13:46   |
 |
danpaul88
Messages: 5795 Registered: June 2004 Location: England
Karma:
|
General (5 Stars) |
|
|
There isn't a built-in method of doing this in C++ (never mind C), but it's not that hard. 5 seconds on Google gives a workable example;
http://stackoverflow.com/questions/1452501/string-replace-in-c
A more efficient solution would be to count how many instances of <search> there are, allocate a new buffer with the required memory size (1 + originalLength + (( length(replace)-(length(match) ) * nMatches)) and then memcpy the unmodified bits of string and as many instances of <replace> as required to build the new string.
Avoids doing unnecessary and costly memory allocations that would be involved in doing it iteratively as in the above example.
[Updated on: Tue, 19 March 2013 13:53] Report message to a moderator
|
|
|