C Program to replace all occurrences of a character in the string
In this program, You will learn how to replace all occurrences of a character in string in c.
Enter a String: Sachin Tendulkar
/* Replace a to @ */
After Replace: S@chin Tendulk@r
Example: How to replace all occurrences of a character in string in c.
#include<stdio.h>
#include<string.h>
int main() {
char str[100];
char ch, rpl;
int i = 0, f = 0;
printf("Enter a string:");
scanf("%[^\n]%*c", str);
printf("Enter which character replace:");
scanf("%c", &ch);
printf("Enter new character for replace:");
scanf(" %c", &rpl);
i = strlen(str);
printf("Before replace:%s", str);
for (int j = 0; j < i; j++) {
if (str[j] == ch) {
str[j] = rpl;
f++;
}
}
if (f > 0) {
printf("\nAfter replace string is:%s", str);
} else {
printf("\nCharacter :%c not found in string :%s", ch, str);
}
return 0;
}
Output:
Enter a string:Welcome to Xiith
Enter which character replace:t
Enter new character for replace:#
Before replace:Welcome to Xiith
After replace string is:Welcome #o Xii#h