View Javadoc

1   package org.apache.mina.example.haiku;
2   
3   /**
4    * @author Apache Mina Project (dev@mina.apache.org)
5    * @version $Rev: $, $Date:  $
6    */
7   public class PhraseUtilities {
8       static int countSyllablesInPhrase(String phrase) {
9           int syllables = 0;
10  
11          for (String word : phrase.split("[^\\w-]+")) {
12              if (word.length() > 0) {
13                  syllables += countSyllablesInWord(word.toLowerCase());
14              }
15          }
16  
17          return syllables;
18      }
19  
20      static int countSyllablesInWord(String word) {
21          char[] chars = word.toCharArray();
22          int syllables = 0;
23          boolean lastWasVowel = false;
24  
25          for (int i = 0; i < chars.length; i++) {
26              char c = chars[i];
27              if (isVowel(c)) {
28                  if (!lastWasVowel
29                          || (i > 0 && isE(chars, i - 1) && isO(chars, i))) {
30                      ++syllables;
31                      lastWasVowel = true;
32                  }
33              } else {
34                  lastWasVowel = false;
35              }
36          }
37  
38          if (word.endsWith("oned") || word.endsWith("ne")
39                  || word.endsWith("ide") || word.endsWith("ve")
40                  || word.endsWith("fe") || word.endsWith("nes")
41                  || word.endsWith("mes")) {
42              --syllables;
43          }
44  
45          return syllables;
46      }
47  
48      static boolean isE(char[] chars, int position) {
49          return isCharacter(chars, position, 'e');
50      }
51  
52      static boolean isCharacter(char[] chars, int position, char c) {
53          return chars[position] == c;
54      }
55  
56      static boolean isO(char[] chars, int position) {
57          return isCharacter(chars, position, 'o');
58      }
59  
60      static boolean isVowel(char c) {
61          return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
62                  || c == 'y';
63      }
64  }