Languages such as Python have the replace(s, old, new [,maxreplace])
method which not only replaces a substring but also allows one to limit the number of replacements made. How can I implement this in C without use of Regex
? It is preferred that the cstring is not modified and can be of any length including 0. This was what I tried. I would like this function to have a parameter max_replacements
such that if and only if it equates to 0, all occurrences are replaced.
char *strnrep(char *haystack, char needle, char replacement, int max_replacements) {
char buf[strlen(haystack) + 1];
int count = 0;
strcpy(buf, haystack);
for (unsigned j = 0; j < strlen(buf); ++j) {
if (buf[j] == needle) count++;
}
int j = 0;
if (max_replacements == 0) {
max_replacements = count;
}
while (j < max_replacements) {
for (int i = 0; buf[i] != '\0'; i++) {
if (buf[i] == needle) {
buf[i] = replacement;
break;
}
}
j++;
}
return strdup(buf);
}
But only works for char
rather than char*
or char[]
...
NOTE This question is NOT duplicate to what one of the commenters is suggesting. I am asking for a specified number of occurrences rather than all.