Reputation: 21
I am looking to create a method that counts the number of syllables within a word. A syllable defined in my project as a contiguous group of vowels but not an 'e' at the end of the word. So the word 'obvious' by this definition only has 2 syllables and the string 'obstinanceeeeeee' has 3 syllables. My attempt is:
protected int countSyllables(String word)
String input = word.toLowerCase();
int i = input.length() - 1;
int syllables = 0, numOfE = 0;
// skip all the e's in the end
while (i >= 0 && input.charAt(i) == 'e') {
i--;
numOfE++;
}
// This counts the number of consonants within a word
int j = 0;
int consonants = 0;
while (j < input.length()) {
if (!isVowel(input.charAt(j))) {
consonants++;
}
j++;
}
// This will return syllables = 1 if the string is all consonants except for 1 e at the end.
if (consonants == input.length() - 1 && numOfE == 1) {
syllables = 1;
}
boolean preVowel = false;
while (i >= 0) {
if (isVowel(input.charAt(i))) {
if (!preVowel) {
syllables++;
preVowel = true;
}
} else {
preVowel = false;
}
i--;
}
return syllables;
}
public boolean isVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
return true;
}
return false;
}
Upvotes: 0
Views: 1763
Reputation: 3604
protected int countSyllables(String word) {
String input = word.toLowerCase();
int i = input.length() - 1;
// skip all the e's in the end
while (i >= 0 && input.charAt(i) == 'e') {
i--;
}
int syllables = 0;
boolean preVowel = false;
while (i >= 0) {
if (isVowel(input.charAt(i))) {
if (!preVowel) {
syllables++;
preVowel = true;
}
} else {
preVowel = false;
}
i--;
}
return syllables;
}
public boolean isVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
return true;
}
return false;
}
I hope this helps. You can start iterating from the end of the string and ignore all the e's before processing/counting the syllables.
Making edit to the original answer. Now will count the word as syllable if it has only one e in the end
protected int countSyllables(String word) {
String input = word.toLowerCase();
int syllables = 0,numOfEInTheEnd=0;
int i = input.length() - 1;
// count all the e's in the end
while (i >= 0 && input.charAt(i) == 'e') {
i--;
numOfEInTheEnd++;
}
if (numOfEInTheEnd == 1) {
syllables = 1;
}
boolean preVowel = false;
while (i >= 0) {
if (isVowel(input.charAt(i))) {
if (!preVowel) {
syllables++;
preVowel = true;
}
} else {
preVowel = false;
}
i--;
}
return syllables;
}
public boolean isVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
return true;
}
return false;
}
Instead of skipping all the trailing e's, now its counting it. If trailing e's is equal to 1, syllables is set to 1. This will work now.
Upvotes: 1