Skip to content

Commit cc2a708

Browse files
Count number of vowels and consonants in a String
How to count number of vowels and consonants in a String? (solution) One of easiest String question you will ever see. You have to write a Java program which will take a String input and print out number of vowels and consonants on that String. For example the if input is "Java" then your program should print "2 vowels and 2 consonants". If you get this question on Interview, you should clarify that whether String can contain numbers, special characters or not e.g. anything other than vowels and consonants.
1 parent 249d0a8 commit cc2a708

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Challenge07.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package challenge07;
2+
3+
import static org.junit.Assert.assertTrue;
4+
import java.util.regex.Pattern;
5+
import org.junit.Test;
6+
7+
/**
8+
* The Class Challenge06.
9+
*
10+
* count number of vowels and consonants in a String.
11+
*/
12+
public class Challenge07 {
13+
14+
public static String vowelAndConstantCount(String input) {
15+
int vowels = 0;
16+
int constants = 0;
17+
18+
for (int i = 0; i < input.length() - 1; i++) {
19+
if (Pattern.matches("[a-zA-Z]{1}", input.substring(i, i + 1))) {
20+
if (Pattern.matches("[a,e,i,o,u]{1}", input.substring(i, i + 1))) {
21+
vowels++;
22+
} else {
23+
constants++;
24+
}
25+
26+
}
27+
}
28+
return vowels + ";" + constants;
29+
}
30+
31+
@Test
32+
public void test() {
33+
assertTrue("3;7".equals(Challenge07.vowelAndConstantCount("{Programming")));
34+
}
35+
}

0 commit comments

Comments
 (0)