Write a function
void inplace(char *str,
const char pattern,
const char* replacement,
size_t mlen)
Input:
str
: a string ending with \0
. the input indicates that we need an inplace algorithm.
pattern
: a letter.
replacement
: a string.
mlen
: the size of the memory holds the string str
starts from the beginning of the memory and that mlen
should be larger than strlen(str)
The final result is still pointed by str
.
Note that all occurrence of pattern should be replaced.
For example,
helelo\0...........
Here "helelo" is the string to replace with '\0'
at the end. After '\0'
there are still L valid bytes. We want to replace "e" by "123".
A simple approach works like this, we go through str
, when a pattern is matched, we shift all the rest with the place to fill the replacement string, then replace the pattern by the replacement.
If the original string is with length n
and contains only e
, we need (n-1) + (n-2) + ... + 1
shifts.
Is there an algorithm that scans the string with only one pass and constant memory cost?