Write a C program to replace all occurrence of a character with another in a string using function. How to replace all occurrences of a character with another in a string using functions in C programming. Logic to replace all occurrences of a character in given string.
Example
Input
Input string: I_love_learning_at_Codeforwin. Input character to replace: _ Input character to replace with: -
Output
String after replacing '_' with '-': I-love-learning-at-Codeforwin
Required knowledge
Basic C programming, Loop, String, Function
Must know –
Logic to replace all occurrence of a character
Below is the step by step descriptive logic to replace all occurrence of a character in a given string.
- Input a string from user, store it in some variable say str.
- Input old character and new character which you want to replace. Store it in some variable say oldChar and newChar.
- Run a loop from start of the string to end. The loop structure should look like while(str[i] != ‘\0’).
- Inside the loop, replace current character of string with new character if it matches with old character. Means, if(str[i] == oldChar) then str[i] = newChar.
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 string size
/* Function declaration */
void replaceAll(char * str, char oldChar, char newChar);
int main()
{
char str[MAX_SIZE], oldChar, newChar;
printf("Enter any string: ");
gets(str);
printf("Enter character to replace: ");
oldChar = getchar();
// Dummy getchar() to eliminate extra ENTER character
getchar();
printf("Enter character to replace '%c' with: ", oldChar);
newChar = getchar();
printf("\nString before replacing: \n%s", str);
replaceAll(str, oldChar, newChar);
printf("\n\nString after replacing '%c' with '%c' : \n%s", oldChar, newChar, str);
return 0;
}
/**
* Replace all occurrence of a character in given string.
*/
void replaceAll(char * str, char oldChar, char newChar)
{
int i = 0;
/* Run till end of string */
while(str[i] != '\0')
{
/* If occurrence of character is found */
if(str[i] == oldChar)
{
str[i] = newChar;
}
i++;
}
}
Read more – Program to replace last occurrence of a character
Output
Enter any string: I_love_Codeforwin. Enter character to replace: _ Enter character to replace '_' with: - String before replacing: I_love_Codeforwin. String after replacing '_' with '-' : I-love-Codeforwin.
Happy coding 😉
Recommended posts
- String programming exercises index.
- C program to find first occurrence of a character in a string.
- C program to remove all occurrences of a character from given 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 repeated characters from a given string.
- C program to search all occurrences of a word in given string.