c program that replace vowels in a string with char
Here is a C program that replaces vowels in a string with a specified character:
#include <stdio.h>
#include <string.h>
int isVowel(char c) {
char vowels[] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
for (int i = 0; i < 10; i++) {
if (c == vowels[i]) {
return 1;
}
}
return 0;
}
void replaceVowels(char *str, char ch) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (isVowel(str[i])) {
str[i] = ch;
}
}
}
int main() {
char str[100];
char ch;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Enter a character to replace vowels with: ");
scanf("%c", &ch);
replaceVowels(str, ch);
printf("String after replacing vowels: %s", str);
return 0;
}
Explanation:
- The program includes the necessary header files
stdio.h
andstring.h
for input/output and string manipulation functions. - The function
isVowel
is defined to check if a given character is a vowel. It takes a characterc
as input and compares it with a list of vowel characters using a loop. If a match is found, it returns 1 (true), otherwise it returns 0 (false). - The function
replaceVowels
is defined to replace vowels in a given string with a specified character. It takes a stringstr
and a characterch
as input. It calculates the length of the string using thestrlen
function and then iterates through each character of the string. If a character is a vowel (determined using theisVowel
function), it is replaced with the specified characterch
. - The
main
function is the entry point of the program. It declares a character arraystr
to store the input string, and a characterch
to store the replacement character. It prompts the user to enter a string usingprintf
andfgets
, and prompts the user to enter a character usingprintf
andscanf
. It then calls thereplaceVowels
function to replace the vowels in the string, and finally prints the modified string usingprintf
.
This program uses two functions, isVowel
and replaceVowels
, to check if a character is a vowel and replace vowels in a string, respectively. The main
function handles input and output and orchestrates the overall execution of the program.