ICSE Class 10 Computer Applications
Question 19 of 46
String Handling — Question 19
Back to all questions 19
Question Question 6
Write a program to input a sentence and arrange words of the string in order of their lengths from shortest to longest.
import java.util.Scanner;
public class KboatWordsSortbyLength
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
str += " ";
int len = str.length();
String word = "";
int wordCount = 0;
char ch;
// calculating no. of words
for (int i = 0; i < len; i++) {
if (str.charAt(i) == ' ') {
wordCount++;
}
}
String wordArr[] = new String[wordCount];
int index = 0;
// storing words in array
for (int i = 0; i < len; i++) {
ch = str.charAt(i);
if (ch != ' ') {
word = word + ch;
}
else {
wordArr[index++] = word;
word = "";
}
}
//bubble sort
for (int i = 0; i < wordCount - 1; i++) {
for (int j = 0; j < wordCount - i - 1; j++) {
if (wordArr[j].length() > wordArr[j + 1].length()) {
String t = wordArr[j];
wordArr[j] = wordArr[j+1];
wordArr[j+1] = t;
}
}
}
// printing
for(int i = 0; i < wordCount; i++) {
System.out.print(wordArr[i] + " ");
}
}
}Output
