How to replace a substring in a string in the C language?
In C language, you can use library functions strstr() and strcpy() to replace a substring within a string. The specific steps are as follows:
- The function strstr()
- Copy the preceding part of the substring to a new string.
- Copy the new substring to a new string for replacement.
- Copy the remaining portion of the substring to a new string.
- The function strcpy() is used to copy a string to another string.
Here is a sample code for replacing a substring in a string:
#include <stdio.h>
#include <string.h>
void replaceSubstring(char *original, char *substring, char *replacement) {
char newString[1000];
char *ptr;
strcpy(newString, original);
while ((ptr = strstr(newString, substring))) {
strcpy(ptr, replacement);
strcpy(ptr + strlen(replacement), ptr + strlen(substring));
}
strcpy(original, newString);
}
int main() {
char str[1000] = "hello world";
printf("Original string: %s\n", str);
replaceSubstring(str, "world", "everyone");
printf("Updated string: %s\n", str);
return 0;
}
In this example, we have defined a replaceSubstring() function to replace a substring in a string. In the main() function, we first output the original string, then call the replaceSubstring() function to replace “world” with “everyone”, and finally output the updated string.