Skip to content

Instantly share code, notes, and snippets.

@TheAlienMann
Created September 8, 2020 14:25
Show Gist options
  • Save TheAlienMann/185774eaeac687305a856b065aee04a5 to your computer and use it in GitHub Desktop.
Save TheAlienMann/185774eaeac687305a856b065aee04a5 to your computer and use it in GitHub Desktop.
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