C Programming: Reverse all the vowels present in a string
38. Reverse Vowels in String
From Wikipedia-
A vowel is a syllabic speech sound pronounced without any stricture in the vocal tract. Vowels are one of the two principal classes of speech sounds, the other being the consonant. Vowels vary in quality, in loudness and also in quantity (length). They are usually voiced and are closely involved in prosodic variation such as tone, intonation and stress.
Write a C program to reverse all the vowels present in a given string. Return the newly created string.
Sample Data:
(“QUICK”) -> “QIUCK”
(“aeiou”) -> “uoiea”
(“AEIou”) -> “uoIEA”
(“Python”) -> “Python”
Sample Solution:
C Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Function to swap vowels in a string
char* test(char* text, int l) {
int i = 0;
int arr[120] = {0}; // Array to store vowel indexes
// Setting vowel indexes to 1
arr['a'] = 1; arr['e'] = 1; arr['i'] = 1; arr['o'] = 1; arr['u'] = 1;
arr['A'] = 1; arr['E'] = 1; arr['I'] = 1; arr['O'] = 1; arr['U'] = 1;
while (i < l) {
// If both characters are vowels, swap them using XOR operations
if (arr[text[i]] == 1 && arr[text[l]] == 1) {
text[i] = text[i] ^ text[l];
text[l] = text[i] ^ text[l];
text[i] = text[i] ^ text[l];
i++;
l--;
}
// Move 'i' to the next vowel or end of the string
while (arr[text[i]] != 1 && i < l) {
i++;
}
// Move 'l' backward to the previous vowel or start of the string
while (arr[text[l]] != 1 && i < l) {
l--;
}
}
return text;
}
int main() {
char string1[80];
int l;
printf("Input a string: ");
scanf("%s", string1);
l = strlen(string1);
// Ensure there are at least two characters in the string to process
if (l - 1 >= 1)
printf("Check vowel positions in the string after swapping: %s", test(string1, l));
}
Output:
Input a string: Check bracket in the said string is valid or not? “uoIEA”
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to reverse only the vowels in a string while keeping the positions of consonants fixed.
- Write a C program to swap the positions of vowels in a string using a two-pointer approach.
- Write a C program to identify all vowels in a string, reverse their order, and then reconstruct the string.
- Write a C program to reverse the order of vowels in a string without affecting the sequence of non-vowel characters.
C Programming Code Editor:
Improve this sample solution and post your code through Disqus.
Previous C Exercise: Multiple two positive numbers represent as string.
Next C Exercise: Longest Palindromic Substring from a given string
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics