mirror of
https://github.com/neovim/neovim.git
synced 2025-09-11 22:08:18 +00:00
refactor: replace_makeprg (#19570)
This commit is contained in:
@@ -1528,3 +1528,45 @@ char_u *reverse_text(char_u *s)
|
||||
|
||||
return rev;
|
||||
}
|
||||
|
||||
/// Replace all occurrences of "what" with "rep" in "src". If no replacement happens then NULL is
|
||||
/// returned otherwise return a newly allocated string.
|
||||
///
|
||||
/// @param[in] src Source text
|
||||
/// @param[in] what Substring to replace
|
||||
/// @param[in] rep Substring to replace with
|
||||
///
|
||||
/// @return [allocated] Copy of the string.
|
||||
char *strrep(const char *src, const char *what, const char *rep)
|
||||
{
|
||||
char *pos = (char *)src;
|
||||
size_t whatlen = STRLEN(what);
|
||||
|
||||
// Count occurrences
|
||||
size_t count = 0;
|
||||
while ((pos = strstr(pos, what)) != NULL) {
|
||||
count++;
|
||||
pos += whatlen;
|
||||
}
|
||||
|
||||
if (count == 0) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
size_t replen = STRLEN(rep);
|
||||
char *ret = xmalloc(STRLEN(src) + count * (replen - whatlen) + 1);
|
||||
char *ptr = ret;
|
||||
while ((pos = strstr(src, what)) != NULL) {
|
||||
size_t idx = (size_t)(pos - src);
|
||||
memcpy(ptr, src, idx);
|
||||
ptr += idx;
|
||||
STRCPY(ptr, rep);
|
||||
ptr += replen;
|
||||
src = pos + whatlen;
|
||||
}
|
||||
|
||||
// Copy remaining
|
||||
STRCPY(ptr, src);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
Reference in New Issue
Block a user