C Programming Code Examples C > Strings Code Examples replace all occurrences of a character in a string replace all occurrences of a character in a string 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. Logic to replace all occurrence of a character 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[x] != '\0'). Inside the loop, replace current character of string with new character if it matches with old character. Means, if(str[x] == oldChar) then str[x] = newChar. /* C program to replace all occurrence of a character with another in a string */ #include <stdio.h> #define maxsize 100 // Maximum string size /* Function declaration */ void replaceAll(char * str, char oldChar, char newChar); int main() { char str[maxsize], 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 x = 0; /* Run till end of string */ while(str[x] != '\0') { /* If occurrence of character is found */ if(str[x] == oldChar) { str[x] = newChar; } x++; } }