Example:
Input string: I_love_C_programming!
Input character to replace: _
Input character to replace with: -
Output after replace: I-love-C-programming!
Required knowledge
Basic C programming, Loop, String, FunctionBefore moving on to this program I recommend you to learn first, replacing first occurrence of a character and last occurrence of a character with another in a string.
Program to replace all occurrences of a character
/** * C program to replace all occurrence of a character with another in a string */ #include <stdio.h> #define MAX_SIZE 100 //Maximum size of the string /* Function declaration */ void replace(char * string, char toReplace, char replaceWith); int main() { char string[MAX_SIZE], toReplace, replaceWith; printf("Enter any string: "); gets(string); printf("Enter character to replace: "); scanf(" %c", &toReplace); printf("Enter character to replace '%c' with: ", toReplace); scanf(" %c", &replaceWith); printf("\nString before replacing: %s\n", string); replace(string, toReplace, replaceWith); printf("String after replacing: %s\n", string); return 0; } /** * Replaces the all occurrence of a character * with another in given string. */ void replace(char * string, char toReplace, char replaceWith) { int i = 0; /* Runs till the end of string */ while(string[i] != '\0') { /* If an occurrence of character is found */ if(string[i] == toReplace) { string[i] = replaceWith; } i++; } }
Output
Enter any string: I_love_C_programming.
Enter character to replace: _
Enter character to replace '_' with: -
String before replacing: I_love_C_programming.
String after replacing: I-love-C-programming.
Enter character to replace: _
Enter character to replace '_' with: -
String before replacing: I_love_C_programming.
String after replacing: I-love-C-programming.
Happy coding ;)
You may also like
- String programming exercises index.
- C program to find first occurrence of a character in a string.
- C program to find all occurrences of a character in a string.
- C program to find lowest frequency character in a string.
- C program to count frequency of each character in a string.
- C program to remove all occurrences of a character from given string.
- C program to remove all repeated characters from a given string.
- C program to search all occurrences of a word in given string.
- C program to trim leading white spaces from a given string.
- C program to trim trailing white spaces from a given string.
- C program to trim leading and trailing white spaces from a given string.