ICSE Class 10 Computer Applications
Question 18 of 46
String Handling — Question 18
Back to all questions 18
Question Question 5
Write a program to input a sentence and arrange each word of the string in alphabetical order.
import java.util.Scanner;
public class KboatWordsSort
{
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].compareTo(wordArr[j + 1]) > 1) {
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
