Essentially what I'm looking for is a standard function that does something like this
void transcpy(char *target, const char *src, const char c)
{
for (int i = 0; i < strlen(target)+1; i++)
if (src[i] == c) target[i] = c;
}
this particular example assumes that target
and src
are the same length, but that's not a necessary precondition for what I'm looking for. Although c
is assumed to appear in src
.
e. g. transcpy(word, "word", 'r");
where word is "____"
would mutate word to be "__r_"
this might just be specific to implementing a hangman game, but it seems like a useful enough function that it might have a standard implementation
I don't think there are a function in standard library that do that, I will implement this as:
char *replace_by_c(char *dest, const char *src, size_t size, char c) {
for (size_t i = 0; i < size; i++) {
if (src[i] == c) {
dest[i] = c;
}
}
return dest;
}
In C, it's common to let the user of a function handle the correct size.
char str_one[42];
char str_two[84];
size_t min = MIN(sizeof str_one, sizeof str_two);
replace_by_c(str_one, str_two, min, 'c');
This let a function to be use in a lot of situations, for example this function can work without NUL
terminate and can handle a character NUL
as c
.
replace_by_c(dest, src, 42, '\0');