-1

I am new to Java. The purpose of the function is to get a word's vowel count. But when given "" as input it returns 1 instead of 0.

Please explain like i am five why this is happening.

public static int getCount(String str) {
        String vowels = "aeiou";
        int answer = 0;

        String strArray[] = str.split("");

        for(String chr : strArray) {
            if ((vowels.contains(chr)) & (chr != "")) {
                answer += 1;
            }
        }
        return answer;
    }

I fixed the code by adding if ((vowels.contains(chr)) & (chr != "")) But this feels ugly

  • 2
    See https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java for an explanation of why `chr != ""` doesn't work. – nanofarad Oct 01 '22 at 16:49

1 Answers1

4

"".split("") returns {""}. If you want to go over the characters, use one of these:

for (char c : str.toCharArray()) {
    if (vowels.indexOf(c) != -1) { ... }
}
for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);
    if (vowels.indexOf(c) != -1) { ... }
}

I prefer the second, it doesn't create a copy of the string.

Rob Spoor
  • 6,186
  • 1
  • 19
  • 20