C Program to Replace All Occurrences of a Character by Another One in a String

Here we’ll see how to replace all occurrences of a character by another one in a string.

Read also: C program to remove all occurrences of a character.

#include <stdio.h>

void replace_char(char* str, char find, char replace){
  int i = 0;
  
  while (str[i] != '\0') {
    /*Replace the matched character...*/
    if (str[i] == find) str[i] = replace;
    
    i++;
  }
}

int main() {
  char str[256], find, replace;
  printf("Enter a string: ");
  fgets(str, sizeof(str), stdin);
  printf("Character to replace: ");
  find = getchar();
  getchar();
  printf("Replace with: ");
  replace = getchar();
  
  replace_char(str, find, replace);
  printf("The string after replacing %c with %c: %s\n", find, replace, str);
  return 0;
}

This program first takes a string as input, then two characters. First character will be replaced by the second one. The replace_char() function replaces the find character with the replace character. It has a loop that iterates through all the characters of the input string, str. If the character of particular position matches with find, that position of the string is assigned with replace.

Here is the output of the program.

Replace all occurrences of a character

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

2
0
0
0
0
0