C Program to replace all occurrences of character in string


In this program, You will learn how to replace all occurrences of 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 character in string in c

Run it Now
#include<stdio.h>
#include<string.h>

int main() {

   char str[100];
   char ch, rpl;
   int i = 0, f = 0;

   printf("Enter a String :");
   fgets(str, 100, stdin);
   strtok(str, "\n");

   printf("\nEnter Which Character Replace :");
   scanf("%c", &ch);

   printf("\nEnter New Character For Replace :");
   scanf(" %c", &rpl);

   i = strlen(str);

   printf("\nBefore 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 :John Smith
Enter Which Character Replace :h
Enter New Character For Replace :@
Before Replace :John Smith
After Replace String is :Jo@n Smit@