How do we use the strreplace function in C language?
In C language, there is no built-in strreplace function to replace a substring in a string. You need to write your own function to achieve this functionality. Here is an example function to replace a substring in a string:
#include <stdio.h>
#include <string.h>
void strreplace(char *str, const char *sub, const char *replace) {
char result[1000];
char *p = strstr(str, sub);
if (p == NULL) {
return;
}
strncpy(result, str, p - str);
result[p - str] = '\0';
sprintf(result + (p - str), "%s%s", replace, p + strlen(sub));
strcpy(str, result);
}
int main() {
char str[1000] = "Hello, world!";
char sub[] = "world";
char replace[] = "C programming";
printf("Before: %s\n", str);
strreplace(str, sub, replace);
printf("After: %s\n", str);
return 0;
}
In this example, we have defined a strreplace function to replace a substring in a string. In the main function, we first print the original string, then call the strreplace function to replace “world” with “C programming”, and finally print the updated string. Feel free to modify the strings and substrings to test the function.