String Exercises
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.
Required knowledge
Basic C programming, C if-else, C for loop, Array, functions, Strings
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++; } }