Write a C Program to replace one character with another character in given string
Replace Character in a String - C Program Example
A C program to replace one character with another character in a given string involves iterating through the characters in the string, copying each character to a new string while replacing the specified character with the new character
, and then displaying the resulting string
C Program to replace one character with another character in given string
#include
int main()
{
char s[10],ch,ch1;
int i;
printf("Enter the string:");
scanf("%s",s);
printf("Enter the 1st Charcater to replace:");
scanf(" %c",&ch);
printf("Enter the 2nd Charcater to feed with replaced character:");
scanf(" %c",&ch1);
printf("Before Replaced the string is:%s\n",s);
for(i=0;s[i];i++)
if(s[i]==ch)
s[i]=ch1;
printf("After the string:%s\n",s);
}
Output:
Enter the string: ELECTRO
Enter the 1st Charcater to Replace : E
Enter the 2nd Charcater to feed with replaced character: R
Before replace the string is: ELECTRO
After the string: RLRCTRO
C Program to Replace Character in a Given String
C Programming
#include
#include
int main() {
char str[100];
char old_char, new_char;
printf("Enter the string: ");
scanf("%s", str);
printf("Enter the character to be replaced: ");
scanf("%c", &old_char);
printf("Enter the replacement character: ");
scanf("%c", &new_char);
// Replace all occurrences of old_char with new_char
for (int i = 0; i < strlen(str); i++) {
if (str[i] == old_char) {
str[i] = new_char;
}
}
// Print the modified string
printf("The modified string is: %s\n", str);
return 0;
}
Example output:
Enter the string: Hello, World!
Enter the character to be replaced: l
Enter the replacement character: o
The modified string is: Heooo, Worod!
Further Reading:
Concatenating Two Strings in C: A Step-by-Step Guide
Design a function to count given character in given string
Design a function to reverse the given string
Design a function to search given character in given string in c
Design a function to reverse the word in given string
Design a function replace the words in reverse order in a given string line
Design a function to find string length in c
Design a Function to print the string character by character
Enroll Now:
[ C-Programming From Scratch to Advanced 2023-2024] "Start Supercharging Your Productivity!"
Contact Us:
- For any inquiries, please email us at [[email protected]].
- Follow us on insta [ electro4u_offical_ ] for updates and tips.
Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!