001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.mina.example.haiku;
020
021/**
022 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
023 */
024public class PhraseUtilities {
025    static int countSyllablesInPhrase(String phrase) {
026        int syllables = 0;
027
028        for (String word : phrase.split("[^\\w-]+")) {
029            if (word.length() > 0) {
030                syllables += countSyllablesInWord(word.toLowerCase());
031            }
032        }
033
034        return syllables;
035    }
036
037    static int countSyllablesInWord(String word) {
038        char[] chars = word.toCharArray();
039        int syllables = 0;
040        boolean lastWasVowel = false;
041
042        for (int i = 0; i < chars.length; i++) {
043            char c = chars[i];
044            if (isVowel(c)) {
045                if (!lastWasVowel
046                        || (i > 0 && isE(chars, i - 1) && isO(chars, i))) {
047                    ++syllables;
048                    lastWasVowel = true;
049                }
050            } else {
051                lastWasVowel = false;
052            }
053        }
054
055        if (word.endsWith("oned") || word.endsWith("ne")
056                || word.endsWith("ide") || word.endsWith("ve")
057                || word.endsWith("fe") || word.endsWith("nes")
058                || word.endsWith("mes")) {
059            --syllables;
060        }
061
062        return syllables;
063    }
064
065    static boolean isE(char[] chars, int position) {
066        return isCharacter(chars, position, 'e');
067    }
068
069    static boolean isCharacter(char[] chars, int position, char c) {
070        return chars[position] == c;
071    }
072
073    static boolean isO(char[] chars, int position) {
074        return isCharacter(chars, position, 'o');
075    }
076
077    static boolean isVowel(char c) {
078        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
079                || c == 'y';
080    }
081}