Write code to remove vowels from the even position in the string. The return type of the output is the string after removing all the vowels.
Input and Output Format:
- Input is a string.
- The output is a string.
Note: Assume the first character is at position 1 in the given string.
Sample Input 1:
commitment
Sample Output 1:
cmmitmnt
Sample Input 2:
capacity
Sample Output 2:
Cpcty
Removing vowels from String in Java
Following are the steps to remove vowels from a string:
- Input a string from the user.
- Pass the string to removeEvenElements() method.
- Inside a method, first, create an empty string buffer.
- Now, iterate over the string and check the index value. Now check, if we found vowels at an even position then remove it.
- At last, just return the string in a string buffer.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
System.out.println(removeEvenElements(s1));
}
public static String removeEvenElements(String s1) {
StringBuffer sb1=new StringBuffer();
for(int i=0;i<s1.length();i++)
if((i%2)==0)
sb1.append(s1.charAt(i));
else if((i%2)!=0)
if(s1.charAt(i)!='a' && s1.charAt(i)!='e' && s1.charAt(i)!='i' && s1.charAt(i)!='o' && s1.charAt(i)!='u')
if(s1.charAt(i)!='A' && s1.charAt(i)!='E' && s1.charAt(i)!='I' && s1.charAt(i)!='O' && s1.charAt(i)!='U')
sb1.append(s1.charAt(i));
return sb1.toString();
}
}
Output
Remove vowels from the string
Write a code to remove all vowels from a string in Java. The return type of the output is the string after removing all the vowels.
Input and Output Format:
- Input is a string.
- The output is a string.
Note: Assume the first character is at position 1 in the given string.
Sample Input 1:
commitment
Sample Output 1:
cmmtmnt
Java Program to Remove vowels from the string
Following are the steps to remove vowels from the string in Java:
- Input a string from the user.
- Add vowels to the list using Arrays.asList();
- Convert string to character array using toCharArray() method.
- Create an empty string buffer.
- Now, traverse over each character and check if the list of vowels does not contain any specified character. If it is true then append that character to the string buffer.
- At last, print the element in a string buffer.
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class RemoveVowel {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
List<Character> list = Arrays.asList('a','e','i','o','u','A','E','I','O','U');
char c[] = str.toCharArray();
StringBuffer sb = new StringBuffer();
for(Character newchar : c ){
if(!list.contains(newchar)){
sb.append(newchar);
}
}
System.out.println(sb);
}
}
Output
Thus, in this way, we learned how to remove vowels from even positions along with removing vowels from the whole string.