previous | start | next

File Word.java

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


previous | start | next