Java: Last n vowels of a given string
Java Regular Expression: Exercise-25 with Solution
Write a Java program to get the last n vowels of a given string.
Sample Solution:
Java Code:
public class test {
public static void main(String[] args) {
String text = "Java";
int n = 2;
System.out.println("Original String: "+text);
System.out.println("Last "+ n + " vowels of a given string: "+validate(text,n));
text = "JavaScript";
n = 2;
System.out.println("Original String: "+text);
System.out.println("Last "+ n + " vowels of a given string: "+validate(text,n));
n = 3;
System.out.println("Last "+ n + " vowels of a given string: "+validate(text,n));
text = "SQLite";
n = 2;
System.out.println("Original String: "+text);
System.out.println("Last "+ n + " vowels of a given string: "+validate(text,n));
text = "The quick brown fox jumps over the lazy dog.";
n = 2;
System.out.println("Original String: "+text);
System.out.println("Last "+ n + " vowels of a given string: "+validate(text,n));
n = 3;
System.out.println("Original String: "+text);
System.out.println("Last "+ n + " vowels of a given string: "+validate(text,n));
n = 15;
System.out.println("Original String: "+text);
System.out.println("Last "+ n + " vowels of a given string: "+validate(text,n));
}
public static String validate(String text, int n) {
String s = text.replaceAll("(?i)[^aeiou]", "");
int l = s.length();
return (n > s.length()) ? "Number of vowels mismatch!!!" : s.substring(s.length() - n);
}
}
Sample Output:
Original String: Java Last 2 vowels of a given string: aa Original String: JavaScript Last 2 vowels of a given string: ai Last 3 vowels of a given string: aai Original String: SQLite Last 2 vowels of a given string: ie Original String: The quick brown fox jumps over the lazy dog. Last 2 vowels of a given string: ao Original String: The quick brown fox jumps over the lazy dog. Last 3 vowels of a given string: eao Original String: The quick brown fox jumps over the lazy dog. Last 15 vowels of a given string: Number of vowels mismatch!!!
Pictorial Presentation:
Flowchart :
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Separate consonants and vowels from a given string.
Next: Check whether a given string is a valid hex code or not.What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/re/java-re-exercise-25.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics