I have already posted similar program where StringTokenizer class of util package has been used to break the sentence into words. In this program index () and substring () functions of String class has been used to break the entered sentence into words and then the words are sorted in ascending order.
Codes of the program
import java.io.*;
class Word
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str1,temp,str2[]=new String[10];
int i,x=0,j;
public void take() throws Exception
{
System.out.println("Enter the sentence:");
str1=br.readLine().trim();
while(true)
{
i=str1.indexOf(' ');
if(i==-1)
break;
str2[x++]=str1.substring(0,i);
str1=str1.substring(i+1);
}
str2[x++]=str1;
for (i=0;i< x;i++)
{
for(j=i+1; j< x;j++)
{
if(str2[i].compareTo(str2[j]) >0)
{
temp=str2[i];
str2[i]=str2[j];
str2[j]=temp;
}
}
}
System.out.println("The words in ascending order\n");
for(i=0;i< x;i++)
System.out.println(str2[i]);
}
public static void main(String args[]) throws Exception
{
Word ob=new Word();
ob.take();
}
}
Technical analysis of this program
We know that indexOf () function searches a character or string from any invoking string and returns the 1st occurance location of the character or string in the invoking string if available otherwise returns -1. A combination of indexOf () and substring () function is used in this above program. Using indexOf () function, 1st occurance location of space is retrieved and using substring () function, the 1st word is extracted and stored in a one dimensional string array. The second call of substring () function within the loop is to remove the word which is stored in the array from the string object. When the loop breaks, the last word is stored in the string array and after that the array is sorted in ascending order.
No comments:
Post a Comment