Method that outputs every vowel from string once

Viewed 33

My current code outputs only the first vowel it encounters. I'd like to know a way to output every vowel that is inputed once.

public static String vowels(String str) {
    String vowels = "auioeëyAUIOEËY";
    for(int i = 0;i < str.length();i++) {
        for(int j = 0;j < str.length();j++) {
            if(str.charAt(i) == vowels.charAt(j)) {
                return "cointains " + vowels.charAt(j) ;
            }
        }   
    }
    return "none";
}
1 Answers

Your inner loop should be using vowels.length() (not str.length()). You need to continue iterating and gathering the matches if you don't want to return the first vowel. You might use a Set. Something like,

public static String vowels(String str) {
    String vowels = "auioeëyAUIOEËY";
    Set<Character> charSet = new LinkedHashSet<>();
    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        for (int j = 0; j < vowels.length(); j++) {
            if (vowels.charAt(j) == ch) {
                charSet.add(ch);
            }
        }
    }
    if (charSet.isEmpty()) {
        return "none";
    }
    return "contains " + charSet.stream().map(String::valueOf)
            .collect(Collectors.joining(" "));
}
Related