Write a program to take a String as input then display the number of x characters word has in ascending order.
Example:
Enter a String
China is world most populous country
Number of 2 characters word : 1
Number of 4 characters word : 1
Number of 5 characters word : 2
Number of 7 characters word : 1
Number of 8 characters word : 1
Here, ascending is 2,4,5,7,8 don't return like 5,2,4,8,7
Hint: length(), charAt(), indexOf(), compareTo(), substring(), equals() can be used.
Note: Array, Split function as well as ternary operators i.e. ? : are not to be used.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Enter a String:");
Scanner in = new Scanner(System.in);
String line = in.nextLine();
for (int i = 1; i <= 100; i++) {
int count = 0;
String chopped = line;
int spaceIndex;
do {
spaceIndex = chopped.indexOf(' ');
if (spaceIndex != -1) {
if (chopped.substring(0, spaceIndex).length() == i) {
count++;
}
chopped = chopped.substring(spaceIndex + 1);
}else{
if (chopped.length() == i) {
count++;
}
}
}
while (spaceIndex != -1);
if (count > 0) {
System.out.println("Number of " + i + " characters word : " + count);
}
}
}
}
Comments
Leave a comment