Skip to content

Fix CheckVowels (#2990) #3004

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 4, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 16 additions & 27 deletions src/main/java/com/thealgorithms/strings/CheckVowels.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
package com.thealgorithms.strings;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
* Vowel Count is a system whereby character strings are placed in order based
* on the position of the characters in the conventional ordering of an
* alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
*/
class CheckVowels {

public static void main(String[] args) {
assert !hasVowels("This is a strings");
assert hasVowels("Hello World");
assert hasVowels("Java is fun");
assert !hasVowels("123hi");
assert hasVowels("Coding vs Programming");
}
public class CheckVowels {
private static final Set<Character> VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));

/**
* Check if a string is has vowels or not
Expand All @@ -22,32 +19,24 @@ public static void main(String[] args) {
* @return {@code true} if given string has vowels, otherwise {@code false}
*/
public static boolean hasVowels(String input) {
if (input.matches("[AEIOUaeiou]")) {
countVowels(input);
return true;
}
return false;
return countVowels(input) > 0;
}

/**
* count the number of vowels
*
* @param input a string prints the count of vowels
*/
public static void countVowels(String input) {
input = input.toLowerCase();
int count = 0;
int i = 0;
while (i < input.length()) {
if (input.charAt(i) == 'a'
|| input.charAt(i) == 'e'
|| input.charAt(i) == 'i'
|| input.charAt(i) == 'o'
|| input.charAt(i) == 'u') {
count++;
public static int countVowels(String input) {
if (input == null) {
return 0;
}
int cnt = 0;
for (char c : input.toLowerCase().toCharArray()) {
if (VOWELS.contains(c)) {
++cnt;
}
i++;
}
System.out.println(count);
return cnt;
}
}