01: /**
02:    This class describes words in a document.
03: */
04: public class Word
05: {
06:    /**
07:       Constructs a word by removing leading and trailing non-
08:       letter characters, such as punctuation marks.
09:       @param s the input string
10:    */
11:    public Word(String s)
12:    {
13:       int i = 0;
14:       while (i < s.length() && !Character.isLetter(s.charAt(i)))
15:          i++;
16:       int j = s.length() - 1;
17:       while (j > i && !Character.isLetter(s.charAt(j)))
18:          j--;
19:       text = s.substring(i, j);      
20:    }
21: 
22:    /**
23:       Returns the text of the word, after removal of the
24:       leading and trailing non-letter characters.
25:       @return the text of the word
26:    */
27:    public String getText()
28:    {
29:       return text;
30:    }
31: 
32:    /**
33:       Counts the syllables in the word.
34:       @return the syllable count
35:    */
36:    public int countSyllables()
37:    {
38:       int count = 0;
39:       int end = text.length() - 1;
40:       if (end < 0) return 0; // The empty string has no syllables
41: 
42:       // An e at the end of the word doesn't count as a vowel
43:       char ch = Character.toLowerCase(text.charAt(end));
44:       if (ch == 'e') end--;
45: 
46:       boolean insideVowelGroup = false;
47:       for (int i = 0; i <= end; i++)
48:       {
49:          ch = Character.toLowerCase(text.charAt(i));
50:          String vowels = "aeiouy";
51:          if (vowels.indexOf(ch) >= 0) 
52:          {
53:             // ch is a vowel
54:             if (!insideVowelGroup)
55:             {
56:                // Start of new vowel group
57:                count++; 
58:                insideVowelGroup = true;
59:             }
60:          }
61:       }
62: 
63:       // Every word has at least one syllable
64:       if (count == 0) 
65:          count = 1;
66: 
67:       return count;      
68:    }
69: 
70:    private String text;
71: }