-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCountVowelsAndConsonants.java
More file actions
52 lines (45 loc) · 1.28 KB
/
CountVowelsAndConsonants.java
File metadata and controls
52 lines (45 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.javamultiplex.string;
import java.util.Scanner;
/**
*
* @author Rohit Agarwal
* @category String Interview Questions
* @problem How many vowels and consonants present in String?
*
*/
public class CountVowelsAndConsonants {
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(System.in);
System.out.println("Enter String : ");
String string = input.next();
// Converting String to lower case
string = string.toLowerCase();
int length = string.length();
// Regular expression that matches a string containing a,e,i,o or u.
String vowelsPattern = "[aeiou]";
/**
* Regular expression that matches a string containing other than
* a,e,i,o or u.
*/
String consonantsPattern = "[b-d]|[f-h]|[j-n]|[p-t]|[v-z]";
String temp = null;
int vowels = 0, consonants = 0;
for (int i = 0; i < length; i++) {
temp = String.valueOf(string.charAt(i));
if (temp.matches(vowelsPattern)) {
vowels++;
} else if (temp.matches(consonantsPattern)) {
consonants++;
}
}
System.out.println("Vowels : " + vowels);
System.out.println("Consonants : " + consonants);
} finally {
if (input != null) {
input.close();
}
}
}
}