santosh wrote:
) Willem wrote:
)> spinoza1111 wrote:
)> ) The point being that a professional, whether or not he uses string.H,
)>
)> Oh so you're wanting a solution that doesn't use string.h ?
)>
)> I've seen some iterations of your code. No offense, but it looks
)> needlessly complex. I think even if we were to replicate strstr()
)> and memcpy() with our own versions, it would still be simpler.
)>
)> But sticking it all in one function, off the top of my head:
)>
)> #include <stdlib.h> /* for malloc() */
)>
)> size_t replace_string(char *string, char *replace, char *with, char *target)
)> {
)> char *string_ptr = string;
)> size_t target_len = 0;
)>
)> while (*string_ptr) {
)> size_t replace_len = 0;
)> while (string_ptr[replace_len] == replace[replace_len]) {
)> replace_len++;
)> }
)> if (replace[replace_len] == 0) {
)> size_t with_len;
)> for (with_len = 0; with[with_len]; with_len++) {
)> if (target) { target[target_len] = with[with_len]; }
)> target_len++;
)> }
)> string_ptr += replace_len;
)> } else {
)> if (target) { target[target_len] = *string_ptr; }
)> target_len++;
)> string_ptr++;
)> }
)> }
)> if (target) { target[target_len] = 0 }
)> target_len++;
)> return target_len;
)> }
)>
)> char *replace(char *string, char *replace, char *with)
)> {
)> char *result;
)> if (result = malloc(replace_string(string, replace, with, 0) + 1)) {
)> replace_string(string, replace, with, result);
)> }
)> return result;
)> }
)>
)>
)> Of course, this will get horridly bad performance for some nasty inputs,
)> especially when the 'replace' string has repeats.
)>
)> To fix that you need Boyer-Moore, IIRC (which I think strstr uses ?)
)
) $ ./willem "aaa" "aaa" "t"
)
) aaa
)
) $ ./willem "aaa" "a" "t"
)
) tta
)
) So a bug somewhere.
You should get into professional testing.
There's even the danger of UB there, looks like.
PS: did you actually randomly throw test cases at it
or did you just spot the bug with the end of string case ?
The fix to the above code would involve some ifs for that edge case,
but perhaps a more elegant solution can be found.
State machine anyone ?
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT