Java examples for java.lang:char
Groups the word into alternating vowel and consonant clusters.
//package com.java2s; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] argv) throws Exception { String word = "java2s.com"; System.out.println(getClustersFromWord(word)); }//from ww w .j a v a 2 s. co m /** * Groups the word into alternating vowel and consonant clusters. * * Note that the even-indexed clusters are always consonants, and the odd-indexed clusters * are always vowels. This means that if the word starts with a vowel, the first cluster is * null * * @param word * In practice this is often a fragment of a word, not the complete word * @return */ static List<String> getClustersFromWord(String word) { List<String> clusters = new ArrayList<String>(); StringBuffer currentCluster = new StringBuffer(); boolean buildingConsonantCluster = true; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (i == 0 && isVowel(c)) { // corner case: we start with a vowel clusters.add(null); // the first cluster is null if we start with a vowel currentCluster.append(c); } else if (buildingConsonantCluster && isVowel(c)) { // we just finished a consonant cluster clusters.add(currentCluster.toString()); currentCluster.delete(0, currentCluster.length()); currentCluster.append(c); buildingConsonantCluster = false; } else if (!buildingConsonantCluster && isConsonant(c)) { // we just finished a vowel cluster clusters.add(currentCluster.toString()); currentCluster.delete(0, currentCluster.length()); currentCluster.append(c); buildingConsonantCluster = true; } else if (buildingConsonantCluster && isConsonant(c)) { // still building a consonant cluster currentCluster.append(c); } else if (!buildingConsonantCluster && isVowel(c)) { // still building vowel cluster currentCluster.append(c); } else { throw new RuntimeException( "I missed a case in the clustering code"); } } clusters.add(currentCluster.toString()); return clusters; } static boolean isVowel(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' || c == 'Y'; } static boolean isConsonant(char c) { return !isVowel(c); } }