C program to replace all occurrence of a character in a string


Enter a string at run time and read a character to replace at console. Then, finally read a new character that has to be placed in place of an old character where ever it occurs inside the string.

Program1

Following is the C program to replace all occurrence of a character −

 Live Demo

#include <stdio.h>
#include <string.h>
int main(){
   char string[100], ch1, ch2;
   int i;
   printf("enter a string : ");
   gets(string);
   printf("enter a character to search : ");
   scanf("%c", &ch1);
   getchar();
   printf("enter a char to replace in place of old : ");
   scanf("%c", &ch2);
   for(i = 0; i <= strlen(string); i++){
      if(string[i] == ch1){
         string[i] = ch2;
      }
   }
   printf("
the string after replace of '%c' with '%c' = %s ", ch1, ch2, string);    return 0; }

Output

When the above program is executed, it produces the following result −

enter a string: Tutorials Point
enter a character to search: i
enter a char to replace in place of old: %
the string after replace of 'i' with '%' = Tutor%als Po%nt
enter a string: c programming
enter a character to search: m
enter a char to replace in place of old: $
the string after replace of 'm' with '$' = c progra$$ing

Program2

Following is the C program to replace at first occurrence −

 Live Demo

#include <stdio.h>
#include <string.h>
int main(){
   char string[100], ch1, ch2;
   int i;
   printf("enter a string : ");
   gets(string);
   printf("enter a character to search : ");
   scanf("%c", &ch1);
   getchar();
   printf("enter a char to replace in place of old : ");
   scanf("%c", &ch2);
   for(i = 0; string[i]!='\0'; i++){
      if(string[i] == ch1){
         string[i] = ch2;
         break;
      }
   }
   printf("
the string after replace of '%c' with '%c' = %s ", ch1, ch2, string);    return 0; }

Output

When the above program is executed, it produces the following result −

Run 1:
enter a string: Tutorial Point
enter a character to search: o
enter a char to replace in place of old: #
the string after replace of 'o' with '#' = Tut#rial Point
Run 2:
enter a string: c programming
enter a character to search: g
enter a char to replace in place of old: @
the string after replace of 'g' with '@' = c pro@ramming

Updated on: 24-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements