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