In this tutorial, we will learn how to write a C program to replace the first occurrence of vowel with ‘-‘.
C Program to replace first occurrence of vowel in a String with ‘-‘
Let’s write the code. The detailed explanation of the program is provided at the end of the code. The brief explanation is provided in the program itself using comments.
#include <stdio.h>
// Function to replace the first occurrence of a vowel with '-'
void replaceFirstVowel(char str[]) {
//String that contains lowercase and uppercase vowels
//We will use this to check the vowels in input string
char vowels[] = "aeiouAEIOU";
int i, j;
// Traverse the string to find the first vowel
for (i = 0; str[i] != '\0'; i++) {
for (j = 0; vowels[j] != '\0'; j++) {
if (str[i] == vowels[j]) {
str[i] = '-'; // Replace the first vowel with '-'
return; // Exit the function after replacing
}
}
}
}
int main() {
char str[100]; // Array to hold input string
// Prompt the user to enter a string
printf("Enter a string: ");
// Read the input string and store in array str[]
fgets(str, sizeof(str), stdin);
// Remove newline character if present
int len = 0;
while (str[len] != '\0') {
if (str[len] == '\n') {
str[len] = '\0';
break;
}
len++;
}
// Call the function to replace the first vowel
replaceFirstVowel(str);
// Print the modified string
printf("Modified string: %s\n", str);
return 0;
}
Output:
Output 1:
Enter a string: Hello World
Modified string: H-llo World
Output 2:
Enter a string: PINK
Modified string: P-NK
Output 3:
Enter a string: Hey!
Modified string: H-y!
Explanation of the program:
replaceFirstVowel() Function:
void replaceFirstVowel(char str[]) {
char vowels[] = "aeiouAEIOU";
int i, j;
for (i = 0; str[i] != '\0'; i++) {
for (j = 0; vowels[j] != '\0'; j++) {
if (str[i] == vowels[j]) {
str[i] = '-'; // Replace the first vowel with '-'
return; // Exit the function after replacing
}
}
}
}
- In this function, we have an array
vowels
that contains lowercase and uppercase vowels. - It returns nested for loop, to check whether any of the input string character matches with the any element of
vowels
array. - When a vowel is found, it is replaced with
'-'
, and the function exits immediately.
main() Function:
- In
main
function, we prompts the user to enter a string usingprintf
function. - It uses
fgets
to read the input string and store it into arraystr[]
. - The program removes the newline from the input string
- It calls the
replaceFirstVowel()
function to replace the first vowel with'-'
. - Finally, it prints the modified string.
Leave a Reply