# Reverse Vowels of a string in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Given a string, the task is to reverse all the vowels present in the given string. For example,

Input-1

a = “tutor”

Output

totur

Explanation − Reversing the string “tutor” will generate the output as “totur.

Input-2

a = “mathematics”

Output

mithametacs

Explanation − Reversing the string “mathematics” will generate the output as “mithametacs”.

## Approach to solve this problem

Given a string, we have to reverse all the vowels present in it. There are several approaches to solve this particular problem but we have to solve this in linear time O(n).

Thus, the better method to solve this problem is to use the Two-Pointer approach in which we will take two pointers low and high which will be pointing initially to the leftmost element and rightmost element. In two nested loops, we will check if the leftmost character is a vowel and the rightmost character is vowel also then swap the element and move the right pointer.

• Take input a string.

• A Boolean function to check if the character is a vowel or not.

• A function reverseVowel(string &str) takes a string as input and reverse the vowels present in the string.

• Initialize two pointers low and high which point to ‘0’ and last character respectively.

• Checking the leftmost and rightmost characters if they are vowels then swap the character in-place and decrement the rightmost pointer.

• Repeating the steps until all the characters of the string are not visited.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool isVowel(char ch) {
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
}
string reverseVowel(string &s){
int low = 0;
int high = s.size() - 1;
while (low < high) {
while (low < high && !isVowel(s[low])) {
low ++;
}
while (low < high && !isVowel(s[high])) {
high --;
}
swap(s[low++], s[high--]);
}
return s;
}
int main(){
string a= "tutorialspoint";
string ans= reverseVowel(a);
cout<<ans;
return 0;
}

## Output

Running the above code will generate the output as,

titorailspount

Since the given string “tutorialspoint” contains vowels, after reversing the vowels, it will generate the output as, “titorailspount”.