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 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 }