Count words, consonants and vowels in a sentence
class CountWordsConsonantsVowelsInSentence {
// ASCII Codes : A-Z = 65-90, a-z = 97-122, 0-9 = 48-57, Enter = 10, Space = 13, Esc = 27
static void count(String str) {
// Corner case :
if(str == null || str == "") {
System.out.println("Invalid input");
return;
}
System.out.println("Original String is : " + str);
char[] chars = str.toCharArray();
int cCounts = 0;
int vCounts = 0;
int wCounts = 1; // assigning 1 if no space means single word
// Remove leading, trailing and multiple spaces
chars = trim(chars);
for(int i = 0; i < chars.length; i++) {
//check if it is letter
if((chars[i] >= 'A' && chars[i] <= 'Z') || (chars[i] >= 'a' && chars[i] <= 'z')) {
// check vowels
if(chars[i] == 'A' || chars[i] == 'a' || chars[i] == 'E' || chars[i] == 'e'
|| chars[i] == 'I' || chars[i] == 'i' || chars[i] == 'O' || chars[i] == 'o'
|| chars[i] == 'U' || chars[i] == 'u') {
vCounts++;
} else {
cCounts++;
}
}
// word counts
if(chars[i] == ' ') {
wCounts++;
}
}
System.out.println("Vowels count : " + vCounts);
System.out.println("Consonants count : " + cCounts);
System.out.println("Words count : " + wCounts);
}
static char[] trim(char[] chars) {
int startIndex = 0;
int endIndex = chars.length;
// Remove leading spaces
while(startIndex < endIndex && chars[startIndex] <= ' ') {
startIndex++;
}
while (startIndex < endIndex && chars[endIndex-1] <= ' ') {
endIndex--;
}
if(startIndex > 0 || endIndex < chars.length) {
return subChars(chars, startIndex, endIndex);
}
return chars;
}
static char[] subChars(char[] chars, int start, int end) {
char[] ch = new char[end-start];
int i = 0;
while(start < end) {
if(chars[start] == ' ') {
int j = start + 1;
// remove all multipl`e spaces
while(j < end && chars[start] == chars[j]) {
start++;
j++;
}
}
ch[i++] = chars[start++];
}
// Since we have removed all spaces so actual lentgh of ch array
// is i that may be less than actual size
char[] newChars = new char[i];
int j = 0;
while(j < i) {
newChars[j] = chars[j];
j++;
}
return ch;
}
public static void main (String[] args) {
String str = "How are you doing today?";
count(str);
str = " How are you doing today? ";
count(str);
}
}
Comments
Post a Comment