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   * @version $Rev: $, $Date:  $
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  }