View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.mina.example.haiku;
20  
21  /**
22   * @author Apache Mina Project (dev@mina.apache.org)
23   */
24  public class PhraseUtilities {
25      static int countSyllablesInPhrase(String phrase) {
26          int syllables = 0;
27  
28          for (String word : phrase.split("[^\\w-]+")) {
29              if (word.length() > 0) {
30                  syllables += countSyllablesInWord(word.toLowerCase());
31              }
32          }
33  
34          return syllables;
35      }
36  
37      static int countSyllablesInWord(String word) {
38          char[] chars = word.toCharArray();
39          int syllables = 0;
40          boolean lastWasVowel = false;
41  
42          for (int i = 0; i < chars.length; i++) {
43              char c = chars[i];
44              if (isVowel(c)) {
45                  if (!lastWasVowel
46                          || (i > 0 && isE(chars, i - 1) && isO(chars, i))) {
47                      ++syllables;
48                      lastWasVowel = true;
49                  }
50              } else {
51                  lastWasVowel = false;
52              }
53          }
54  
55          if (word.endsWith("oned") || word.endsWith("ne")
56                  || word.endsWith("ide") || word.endsWith("ve")
57                  || word.endsWith("fe") || word.endsWith("nes")
58                  || word.endsWith("mes")) {
59              --syllables;
60          }
61  
62          return syllables;
63      }
64  
65      static boolean isE(char[] chars, int position) {
66          return isCharacter(chars, position, 'e');
67      }
68  
69      static boolean isCharacter(char[] chars, int position, char c) {
70          return chars[position] == c;
71      }
72  
73      static boolean isO(char[] chars, int position) {
74          return isCharacter(chars, position, 'o');
75      }
76  
77      static boolean isVowel(char c) {
78          return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
79                  || c == 'y';
80      }
81  }