Skip to content

Commit e7ff986

Browse files
authored
Fix CheckVowels (TheAlgorithms#3004)
Close TheAlgorithms#2990
1 parent 8d099ee commit e7ff986

File tree

1 file changed

+16
-27
lines changed

1 file changed

+16
-27
lines changed
Lines changed: 16 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
11
package com.thealgorithms.strings;
22

3+
import java.util.Arrays;
4+
import java.util.HashSet;
5+
import java.util.Set;
6+
37
/**
48
* Vowel Count is a system whereby character strings are placed in order based
59
* on the position of the characters in the conventional ordering of an
610
* alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
711
*/
8-
class CheckVowels {
9-
10-
public static void main(String[] args) {
11-
assert !hasVowels("This is a strings");
12-
assert hasVowels("Hello World");
13-
assert hasVowels("Java is fun");
14-
assert !hasVowels("123hi");
15-
assert hasVowels("Coding vs Programming");
16-
}
12+
public class CheckVowels {
13+
private static final Set<Character> VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
1714

1815
/**
1916
* Check if a string is has vowels or not
@@ -22,32 +19,24 @@ public static void main(String[] args) {
2219
* @return {@code true} if given string has vowels, otherwise {@code false}
2320
*/
2421
public static boolean hasVowels(String input) {
25-
if (input.matches("[AEIOUaeiou]")) {
26-
countVowels(input);
27-
return true;
28-
}
29-
return false;
22+
return countVowels(input) > 0;
3023
}
3124

3225
/**
3326
* count the number of vowels
3427
*
3528
* @param input a string prints the count of vowels
3629
*/
37-
public static void countVowels(String input) {
38-
input = input.toLowerCase();
39-
int count = 0;
40-
int i = 0;
41-
while (i < input.length()) {
42-
if (input.charAt(i) == 'a'
43-
|| input.charAt(i) == 'e'
44-
|| input.charAt(i) == 'i'
45-
|| input.charAt(i) == 'o'
46-
|| input.charAt(i) == 'u') {
47-
count++;
30+
public static int countVowels(String input) {
31+
if (input == null) {
32+
return 0;
33+
}
34+
int cnt = 0;
35+
for (char c : input.toLowerCase().toCharArray()) {
36+
if (VOWELS.contains(c)) {
37+
++cnt;
4838
}
49-
i++;
5039
}
51-
System.out.println(count);
40+
return cnt;
5241
}
5342
}

0 commit comments

Comments
 (0)