Categories
Class 11 Class 12

Arrange Words Alphabetically ISC 2012 Practical

Write a program to accept a sentence as input. The words in the string are to be separated by a blank. Each word must be in uppercase. The sentence is terminated by either ‘.’, ‘!’ or ‘?’. Perform the following tasks:

  1. Obtain the length of the sentence (measured in words).
  2. Arrange the sentence in alphabetical order of the words.

Test your program with the sample data and some random data.

Example 1:
INPUT:
NECESSITY IS THE MOTHER OF INVENTION.
OUTPUT:
LENGTH: 6
REARRANGED SENTENCE:
INVENTION IS MOTHER NECESSITY OF THE

Example 2:
INPUT:
BE GOOD TO OTHERS.
OUTPUT:
LENGTH: 4
REARRANGED SENTENCE:
BE GOOD OTHERS TO

import java.io.*;
import java.util.StringTokenizer;
class Alphabetical{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Sentence: ");
        String s = br.readLine();
        s = s.trim();
        char last = s.charAt(s.length() - 1);
        if(last != '.' && last != '?' && last != '!'){
            System.out.println("INVALID SENTENCE!");
            return;
        }
        s = s.toUpperCase();
        StringTokenizer st = new StringTokenizer(s, " .?!,");
        int len = st.countTokens();
        System.out.println("LENGTH: " + len);
        String words[] = new String[len];
        for(int i = 0; i < len; i++)
            words[i] = st.nextToken();
        for(int i = 0; i < len; i++){
            for(int j = 0; j < len - 1 - i; j++){
                if(words[j].compareTo(words[j + 1]) > 0){
                    String temp = words[j];
                    words[j] = words[j + 1];
                    words[j + 1] = temp;
                }
            }
        }
        String r = "";
        for(int i = 0; i < len; i++)
            r += words[i] + " ";
        r = r.trim();
        System.out.println("REARRANGED SENTENCE:\n" + r);
    }
}

By admin

I am a Computer Science teacher in one of the renowned schools in India. I teach Java programming language to my students, and I maintain a website happycompiler.com

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.