The Program in C to input a text and replace an entered string occurring within the text with an equal number of “*”, at all occurring is given below:
#include <stdio.h>
#include <string.h>
void replace_string(char* text, char* find, char* replace) {
char* p = text;
while ((p = strstr(p, find)) != NULL) {
int diff = strlen(replace) - strlen(find);
if (diff != 0) {
memmove(p + strlen(replace), p + strlen(find), strlen(p + strlen(find)) + 1);
}
memcpy(p, replace, strlen(replace));
p += strlen(replace);
}
}
int main() {
char text[1000];
printf("Enter text: ");
scanf("%[^\n]", text);
char find[100];
printf("Enter string to be replaced: ");
scanf("%s", find);
char replace[strlen(find) + 1];
for (int i = 0; i < strlen(find); i++) {
replace[i] = '*';
}
replace[strlen(find)] = '\0';
replace_string(text, find, replace);
printf("Text with replaced string: %s\n", text);
return 0;
}
Output:
Enter text: you are great
Enter string to be replaced: you
Text with replaced string: *** are great
Pro-Tips💡
This code is a simple program that replaces all occurrences of a given string within another string with a different string.
The replace_string
function takes in three parameters: a pointer to the text string, a pointer to the string to find, and a pointer to the string to replace it with.
The function then uses the strstr
function to find all occurrences of the find string within the text string, and then uses the memmove
and memcpy
functions to replace them with the replace string.
The main
function prompts the user to enter the text and the string to find, then creates a new string to replace it with consisting of the same number of asterisks as the length of the find string.
It then calls the replace_string
function to perform the replacement and prints out the modified text.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.