Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
print out the first n vowels in a given string
private static int countMatches(Matcher matcher) {
int counter = 0;
while (matcher.find())
counter++;
return counter;
}
@Override
public String firstNVowels(String str, int n) {
Pattern pattern = Pattern.compile("(?i)[aeiou]");
Matcher matcher = pattern.matcher(str);
System.out.println(String.format("Number of matchers: %d", countMatches(matcher)));
if (countMatches(matcher) < n) {
return "invalid";
}
StringBuilder result = new StringBuilder();
while (matcher.find()) {
for (int i = 1; i <= n; i++) {
result.append(matcher.group(i));
}
}
return result.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment