Remove vowels 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' from given string.
Example 1:
Input: str ="Hello World" Output: Hll Wrld
Approach
Java
import java.util.Arrays;
import java.util.List;
public class RemoveVowels {
public static void main(String[] args) {
String str = "Hello World";
String s = removeVowels(str);
System.out.println(s);
}
// method for remove vowels
private static String removeVowels(String str) {
// vowels array
Character[] vovels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
List<Character> v = Arrays.asList(vovels);
char[] st = str.toCharArray();
int index = 0;
// iterate till end of list
for (int i = 0; i < st.length; i++) {
// if not vowels
if (!v.contains(st[i])) {
st[index] = st[i];
index++;
}
}
// remove extra element
return new String(st).substring(0, index);
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to check the
//character is vowel or not
bool isVowel(char ch)
{
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
return true;
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
return true;
return false;
}
//function to remove the vowels
//from the string
void removeVowels(string &str)
{
int index=0;
for(int i=0;i<str.size();i++)
{
if(!isVowel(str[i]))
str[index++]=str[i];
}
str.resize(index);
}
int main()
{
string str="Hello World";
removeVowels(str);
cout<<str<<"\n";
return 0;
}
No comments:
Post a Comment