1
1
package com .thealgorithms .strings ;
2
2
3
+ import java .util .Arrays ;
4
+ import java .util .HashSet ;
5
+ import java .util .Set ;
6
+
3
7
/**
4
8
* Vowel Count is a system whereby character strings are placed in order based
5
9
* on the position of the characters in the conventional ordering of an
6
10
* alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
7
11
*/
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' ));
17
14
18
15
/**
19
16
* Check if a string is has vowels or not
@@ -22,32 +19,24 @@ public static void main(String[] args) {
22
19
* @return {@code true} if given string has vowels, otherwise {@code false}
23
20
*/
24
21
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 ;
30
23
}
31
24
32
25
/**
33
26
* count the number of vowels
34
27
*
35
28
* @param input a string prints the count of vowels
36
29
*/
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 ;
48
38
}
49
- i ++;
50
39
}
51
- System . out . println ( count ) ;
40
+ return cnt ;
52
41
}
53
42
}
0 commit comments