Richard said:
Richard G. Riley wrote:
[...]
So what you might want to then do is to "strcpy" the rest of the
source string over the start of the string you just located. Below is
untested but you will get the idea:
char * refFound = strstr(refBuffer,refStringToLocate);
if(refFound){
/* assumes null terminated character buffer)
strcpy(refFound, refFound+strlen(refStringToLocate));
}
Do NOT use strcpy() if the source and destination might
overlap, as they might in this situation. If refBuffer holds
"Now is the time for all good parties to come to the aid of Man"
all is well if refStringToLocate is "come" but all is NOT well
if refStringToLocate is "time".
refStringToLocate is obviously not in the buffer : otherwise there
would be no need to locate it. But to clarify I am assuming that
refStringToLocate is a seperate buffer.
Doesn't matter; it's the potential overlap in strcpy()
that can cause trouble. Let's consider the "time" case above.
strstr() finds "time" at position 11 in refBuffer, extending
through position 14. strcpy() will then try to copy positions
15-62 (if I've counted correctly, the terminating '\0' is at
position 62) to positions 11-58. Positions 15-58 are therefore
both sources and destinations; that's the overlap. From the
Standard, 7.21.2.3/2: "[...] If copying takes place between
objects that overlap, the behavior is undefined."
The reason for the undefinedness is to allow implementations
maximum freedom to produce a fast and efficient strcpy(); the
Standard does not require that copying take place from left to
right, nor in units of one char at a time. Implementations that
don't (always) go left-to-right or that handle several chars in
each "chunk" can easily get bollixed by overlap, so behavior on
overlap is not specified. There's similar language for memcpy(),
for sprintf(), and for various other things. If you need to
"slide" things within a single array, memmove() is your friend.