Tuesday, January 29, 2013

Java : Sorting Strings with Ignoring Case

Hello everyone lately I've been doing some java task and I have to sort the String I inputted without looking into it's case. I have to sort it even if there are uppercase letters or lowercase because in computer programming or keyboards or the letters you are looking at Uppercase is not always equal to Lowercase unless you do ignore their case. The computer relies on it's ascii value so the "A" is not equal to "a". I have to sort my inputted String and when I use the simple compareTo method of java I won't be able to solve this so
I created a method that will have 2 arguments/parameters those 2 will be use in comparing, then I convert them into lowercase :) here's how I did it.

import java.io.*;
public class StringSort {
 public static void main(String args[]) throws IOException{
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String userInput = "";

  System.out.print("Enter a string to sort : ");
  userInput = br.readLine();

  String sortedString[] = userInput.split("");

  //sort the string
  for(int i = 1; i<sortedString.length; i++) {
   for(int j = i+1; j<sortedString.length; j++) {
    if(sortString(sortedString[i], sortedString[j])) {
     String tmp = sortedString[i];
     sortedString[i] = sortedString[j];
     sortedString[j] = tmp;
    }
   }
  }

  for(int i = 1; i<sortedString.length; i++) {
   System.out.print(sortedString[i]);
  }
 }

 public static boolean sortString(String c1, String c2) {
  c1 = c1.toLowerCase();
  c2 = c2.toLowerCase();

  if(c1.compareTo(c2) > 0) {
   return true;
  } else {
   return false;
  }
 }
 
}

No comments:

Post a Comment