Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Reverse only the vowels of a given string

C++ String: Exercise-19 with Solution

Write a C++ program to reverse only the vowels of a given string.

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.

Example-1:

Input: w3resource

Output: w3resuorce

Example-2:

Input: Python

Output: Python

Example-3:

Input: Hello

Output: Holle

Example-4:

Input: USA

Output: ASU

Sample Solution:

C++ Code:

#include <iostream>

#include<algorithm>
#include <stack>

using namespace std;
 
string reverse_vowels(string ostr) {
    vector<int>vec_data;
    string result_str=ostr;
    for(int i=0;i<ostr.length();i++) {
    	if(ostr[i]=='A' or ostr[i]=='E' or ostr[i]=='I' or ostr[i]=='O' or ostr[i]=='U' or ostr[i]=='a' or ostr[i]=='e' or ostr[i]=='i' or ostr[i]=='o' or ostr[i]=='u' ) 
			vec_data.push_back(i);
       }
   for(int i=0;i<vec_data.size()/2;i++) swap(result_str[vec_data[i]],result_str[vec_data[vec_data.size()-1-i]]);
        return result_str;
    }
 

int main()
{
  char str1[] = "w3resource";
  cout << "Original string: " << str1;
  cout << "\nAfter reversing the vowels of the said string: " << reverse_vowels(str1);
  char str2[] = "Python";
  cout << "\n\nOriginal string: " << str2;
  cout << "\nAfter reversing the vowels of the said string: " << reverse_vowels(str2);
  char str3[] = "Hello";
  cout << "\n\nOriginal string: " << str3;
  cout << "\nAfter reversing the vowels of the said string: " << reverse_vowels(str3);
  char str4[] = "USA";
  cout << "\n\nOriginal string: " << str4;
  cout << "\nAfter reversing the vowels of the said string: " << reverse_vowels(str4);
  return 0;    
}

Sample Output:

Original string: w3resource
After reversing the vowels of the said string: w3resuorce

Original string: Python
After reversing the vowels of the said string: Python

Original string: Hello
After reversing the vowels of the said string: Holle

Original string: USA
After reversing the vowels of the said string: ASU

Flowchart:

Flowchart: Reverse only the vowels of a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ programming to find the length of the longest valid (correct-formed) parentheses substring of a given string.

Next: Write a C++ program to find the length of the longest palindrome in a given string (uppercase or lowercase letters).

What is the difficulty level of this exercise?