C Program To Replace A Character in String
Learn How To Replace A Character in String in C Programming with another User Defined Character. This C Program To Exchange Characters in an Array of Characters, also known as Strings uses three Block Structures:
- For Loop
- While Loop
- If – Else Block Structure
How To Take Two Characters From User
In the second method, we have taken Two Character Inputs from the User. However, when you try it in the normal way, you will get the Input of only one character. To take both the characters from the User, you will have to add a space before %c in the scanf() method. This will ignore any spaces before the scanf().
Also Read: C Program To Remove Vowels From A String
Method 1: Code To Replace Character in String with * in C Programming
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<stdio.h> int main() { char array[20]; int counter; printf("\nEnter A String: "); scanf("%s", array); printf("\nOriginal String: %s\n", array); while(array[counter] != '\0') { if(array[counter] == 'a') { array[counter] = '*'; } counter++; } printf("\nReplaced Character in String: %s\n", array); printf("\n"); return 0; } |
Output

Also Read: Print India’s Map in C Programming (Obfuscated Code)
Method 2: C Program To Replace Character in a String with User – Defined Character
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include<stdio.h> int main() { char array[20], char1, char2; int counter; printf("\nEnter A String: "); scanf("%s", array); printf("\nOriginal String: %s\n", array); printf("\nEnter Character in String To Be Replaced: "); scanf(" %c", &char1); printf("\nEnter The Character For Replacement: "); scanf(" %c", &char2); while(array[counter] != '\0') { if(array[counter] == char1) { array[counter] = char2; } counter++; } printf("\nReplaced Character in String: %s\n", array); printf("\n"); return 0; } |
Output:

If you have have any compilation errors or doubts with Code to Replace A Character in String in C Programming, let us about it in the Comment Section below.
What is the difference between == and = operator?
In the above program the character is not taking to replaced.I am unable to see the results of this code.please help me
replacing a character by 2 alphabets then wat to do??
sch as in i=Tushar i want to replace u by mf i.e Tmfshar
how to replace only the first occurance of string
In this code the variable counter doesn’t having any values