KnowledgeBoat Logo

Computer Applications

Write a program to input a sentence and arrange words of the string in order of their lengths from shortest to longest.

Java

Java String Handling

2 Likes

Answer

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

BlueJ output of Write a program to input a sentence and arrange words of the string in order of their lengths from shortest to longest.

Answered By

2 Likes


Related Questions