Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

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

$
0
0

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

The post C Program to Replace All Occurrences of a Character by Another One in a String appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>