Replace a sub-string in a string in C
Understanding String Manipulation
Replacing a sub-string in a string means finding a specific sequence of characters and replacing it with another sequence.
We will explore three different methods to achieve this in C.
Method 1: Using Loop
This method iterates through the string and replaces occurrences of the sub-string.
#include <stdio.h>
#include <string.h>
void replaceSubstring(char *str, char *oldWord, char *newWord) {
char buffer[1000];
char *pos;
int index = 0, oldLen = strlen(oldWord);
buffer[0] = '\0';
while ((pos = strstr(str, oldWord)) != NULL) {
strncat(buffer, str, pos - str);
strcat(buffer, newWord);
str = pos + oldLen;
}
strcat(buffer, str);
strcpy(str, buffer);
}
int main() {
char str[1000] = "Hello World!";
replaceSubstring(str, "World", "C");
printf("Modified String: %s", str);
return 0;
}
Output: Hello C!
Method 2: Using Recursion
This method replaces the sub-string recursively.
#include <stdio.h>
#include <string.h>
void replaceRecursive(char *str, char *oldWord, char *newWord, char *buffer) {
char *pos = strstr(str, oldWord);
if (!pos) {
strcat(buffer, str);
return;
}
strncat(buffer, str, pos - str);
strcat(buffer, newWord);
replaceRecursive(pos + strlen(oldWord), oldWord, newWord, buffer);
}
int main() {
char str[1000] = "I love programming";
char buffer[1000] = "";
replaceRecursive(str, "love", "enjoy", buffer);
printf("Modified String: %s", buffer);
return 0;
}
Output: I enjoy programming
Method 3: Using String Functions
This method uses C's built-in strstr() and strcpy() functions.
#include <stdio.h>
#include <string.h>
void replaceUsingFunctions(char *str, char *oldWord, char *newWord) {
char buffer[1000];
char *pos = strstr(str, oldWord);
if (!pos) return;
strncpy(buffer, str, pos - str);
buffer[pos - str] = '\0';
strcat(buffer, newWord);
strcat(buffer, pos + strlen(oldWord));
strcpy(str, buffer);
}
int main() {
char str[1000] = "Replace old text";
replaceUsingFunctions(str, "old", "new");
printf("Modified String: %s", str);
return 0;
}
Output: Replace new text