Comparing strings in Java?

102 Views Asked by At

I have few strings whom I have to compare and the print the smallest,For eg:

A0< A1

A12< A22

A< B

12<23

a12< a21

Note:The string could be only number or only alphabet or can be mixture of both we have to compare it and print the smallest one first. My procedure:I checked the first character of string by "charAt " if its a letter I used compare to function if its a number I used IntParse method. But I could not figure out how to compare alphanumerical string like A12 < A21.

if ((assignment.getAssigncode()[i]).matches("[a-zA-Z]") && 
   ((assignment.getAssigncode()[j]).matches("[a-zA-Z]"))) {
   if ((assignment.getAssigncode()[i]).compareTo((assignment.getAssigncode()[j])) > 0) {
      swap();
   } else {
       if (Integer.parseInt((assignment.getAssigncode()[i])) > 
           Integer.parseInt((assignment.getAssigncode()[j]))) {
           swap();
       }
   }
}
1

There are 1 best solutions below

0
On

First we have to check that the first character of string is a Alphabet or not using 'charAt(0)' function,if so then we have to compare string1 charAt(0) and string2 'charAt(0)' if string1charAt(0) is less then we could swap,else if both the first character are equal the we could use substring(1) method to convert the remaining string to integer and then we can directly compare it.

       if (((assignment.getAssigncode()[i]).charAt(0)) >= 65 && ((assignment.getAssigncode()[i]).charAt(0)) <= 122 && ((assignment.getAssigncode()[j]).charAt(0)) >= 65 && ((assignment.getAssigncode()[j]).charAt(0)) <= 122) {
 if (((assignment.getAssigncode()[i]).charAt(0)) > ((assignment.getAssigncode()[j]).charAt(0))) {
swap();}
}
else if (((assignment.getAssigncode()[i]).charAt(0)) == ((assignment.getAssigncode()[j]).charAt(0))) {
                                                int y = Integer.parseInt((assignment.getAssigncode()[i]).substring(1));
                                                int v = Integer.parseInt((assignment.getAssigncode()[j]).substring(1));
                                                if (y > v) {
swap();
}
}

  else {
                                                if (Integer.parseInt((assignment.getAssigncode()[i])) > Integer.parseInt((assignment.getAssigncode()[j]))) {
swap();
}