C Programming: Reverse all the vowels present in a string
C String: Exercise-38 with Solution
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));
}
Sample Output:
Input a string: Check bracket in the said string is valid or not? “uoIEA”
Flowchart :
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming-exercises/string/c-string-exercise-38.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics