Skip to content

Split a String Based on Vowels and Consonants

Java solution to split a string based on vowels and consonants.

Advertisements

Problem

Write a function that takes a string, breaks it up and returns it with vowels first, consonants second. For any character that’s not a vowel (like special characters or spaces), treat them like consonants.

Examples

split("abcde") ➞ "aebcd"

split("Hello!") ➞ "eoHll!"

split("What's the time?") ➞ "aeieWht's th tm?"

Notes

  • Vowels are a, e, i, o, u.
  • Define a separate isVowel() function for easier to read code (recommendation).

Solutions

Advertisements
public class Challenge {
  public static String split(String str) {
    String str1 = str.replaceAll("(?i)[^aeiou]", "");
    String str2 = str.replaceAll("(?i)[aeiou]", "");
    return str1 + str2;
  }
}
public class Challenge {
  public static String split(String str) {
        String vowels = "";
        String consonants = "";
        vowels = vowels.concat(str.replaceAll("a|A|e|E|i|I|o|O|u|U",""));
        consonants = consonants.concat(str.replaceAll("[^a|A|e|E|i|I|o|O|u|U]",""));
        return  consonants.concat(vowels);
  }
}
import java.util.*;
public class Challenge {
	public static void main(String args[]){
		Scanner Sc=new Scanner(System.in);
		String s=Sc.next();
		String result=split(s);
		System.out.println(result);
	}
	public static String split(String str) {
		String vow="";
		String rem="";
		for(int i=0;i<str.length();i++){
			boolean check=isVowel(str.charAt(i));
			if(check){
				vow=vow+str.charAt(i);
			}
			else{
				rem=rem+str.charAt(i);
			}
		}
		return vow+rem;
	}
	public static boolean isVowel(char ch){
		String s="aeiouAEIOU";
		for(int i=0;i<s.length();i++){
			if(s.charAt(i)==ch){
				return true;
			}
		}
		return false;
	}
}

See also  Remove duplicates from an array using Lodash

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.