First X vowels from a string in C++


In this problem, we are given string str[] of size N and an integer X. Our task is to create a program to print First X vowels from a string.

We will print first X vowels from the string and if less than X vowels are present, print -1.

Let's take an example to understand the problem,

Input: str = "learn C programming language", X = 5
Output: e, a, o, a, i
Vowels are a, e, i, o, u

Solution Approach

A simple solution to the problem is by traversing the string character by charter. And storing all the vowels of the string to a vowels string. And if the length of this string is equal to X, return it. If all vowels of the string cannot make the count upto X, return -1.

Example

Program to illustrate the working of our solution

#include <iostream>
#include <string.h>
using namespace std;
bool isaVowel(char c){
   c = tolower(c);
   if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
      return true;
   return false;
}
string findXVowelsString(string s, int x){
   string vowelsString = "";
   for (int i = 0; i < s.length(); i++) {
      if (isaVowel(s[i]))
         vowelsString += s[i];
      if (vowelsString.length() == x) {
         return vowelsString;
      }
   }
   return "-1";
}
int main(){
   string str = "learn C programming language";
   int x = 5;
   cout<<"The first "<<x<<" vowels from the string are "<<findXVowelsString(str, x);
   return 0;
}

Output

The first 5 vowels from the string are eaoai

Updated on: 01-Feb-2022

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements