Wednesday, 12 June 2013

String Compare function

String compare function is used to sort a string by name. The string entered by user is scanned word by word. This function arrange the string in alphabetic order.
If the second word appear earlier to first word, then this function generates a negative value i.e. less than Zero.
If the second word appear after the first word, then this function generates a positive value i.e. greater than Zero.
If the second word is same to the first word, then this function generates Zero.

Program for string compare function:


class Strcomp
{
public static void main(String arg[])
{
String arr[]={"this","is","the","duty","of","every","citizen","to","serve","his","country"};
String t;
int i,j;
for(i=0;i<arr.length;i++)
{
for(j=i+1;j<arr.length;j++)
{
if(ar[j].compareTo(arr[i])<0)
{
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
for(i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}

Following is the output of the above code:



full details in json
Proudly Powered by Blogger.