C Program to Replace Character in String

In this example, You learn about c program to replace character in string.

Here you learn program to replace a character in a string in C, You read a string and character then replace a character with another character read from user using function.

C Program to Replace character in String


#include<stdio.h>
#include<string.h> 

void replaceChar(char *); 

int main() { 
	char str[20]; 
	printf("\n Enter a String : ");
	gets(str); 
	replaceChar(str); 
	return 0; 
}
 
void replaceChar(char *p) {
 	int i,count=0; 	
	char c,r; 
    printf("\n Enter Character You Want To Replace : ");
	scanf("%c",&c);  
	fflush(stdin);
	printf("\n Enter New Character : "); 
	scanf("%c",&r); 
	for(i=0;*(p+i)!='\0';i++) 	
	{	 		
		if(*(p+i)==c)
		{ 			
			count++;
			*(p+i)=r; 		
		} 	
	}		 
	printf("\n New String : "); 
	puts(p); 
	printf("\n '%c' Was Replaced %d Times.",c,count); 
}

Output

 Enter a String : Codeamy@in

 Enter Character You Want To Replace : @

 Enter New Character : .

 New String : Codeamy.in

 '@' Was Replaced 1 Times.
I hope you enjoy this example if you have doubt leave it in the comment box below.
Happy Coding 😊

If you have any doubts, Please let me know

Previous Post Next Post

Contact Form