The challenge
Return the number (count) of vowels in the given string.
We will consider a, e, i, o, u
as vowels for this challenge (but not y
).
The input string will only consist of lower case letters and/or spaces.
The solution in Java code
Option 1:
public class Vowels {
public static int getCount(String str) {
int vowelsCount = 0;
char[] chars = str.toCharArray();
for (char c : chars) {
if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u')
vowelsCount++;
}
return vowelsCount;
}
}
Option 2:
public class Vowels {
public static int getCount(String str) {
return str.replaceAll("(?i)[^aeiou]", "").length();
}
}
Option 3:
public class Vowels {
public static int getCount(String str) {
return (int) str.chars().filter(c -> "aeiou".indexOf(c) >= 0).count();
}
}
Test cases to validate our solution
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class VowelsTest {
@Test
public void testCase1() {
assertEquals("Nope!", 5, Vowels.getCount("abracadabra"));
}
}