Wednesday, 11 February 2015

How To Sort String In Java

This tutorial demonstrate how to sort string in java using compareTo() you can see from output "F" before all word because it is in the uppercase if you want to ignore case than use comareToIgnorecase()

compareTo Example in Java:

Often we need to know which strings are identical for sorting purpose to do this java has a method compareTo() this method compare two strings and returned  its result as shown below
less than zero = string is less than string
greatet than zero = string is greater than string
Zero = The string are equal

CODING:

class stringsorting
{
public static void main(String args[])
{
String arr[] = {"e","d","f","b","a","F"};
System.out.println("Before sorting:");

for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
System.out.println("After sorting:");
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[j].compareTo(arr[i])<0) 
{
String t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
System.out.println(arr[i]);
}
}
}

OUTPUT:




No comments:

Post a Comment