Sort java string arrays by size and java string Arrays
If two strings are compared directly, The packet: the operator> is undefined for The argument type (s) java. lang. String, java. lang. String is incorrect.
To compare the size of a string, you can use the string length or the ASCII value of the characters in the string. The former is too simple and will not be recorded.
The character string is compared with the ASCII code. The rule is:
1. Compare the ASCII code size of the first letter
2. If the first letter is the same, compare the ASCII value of the subsequent letter
3. If a string starts to contain another character string, the length of the string is considered to be long. For example: abc> AB
Note: Use commons-logging-1.2.jar in code to sort from small to large
1 import org. apache. commons. logging. log; 2 import org. apache. commons. logging. logFactory; 3 4/** 5 * sort string arrays 6 * @ author panjianghong 7 * @ since 2016/8/31 8 **/9 public class StringSort {10 11 private static final Log _ log = logFactory. getLog (StringSort. class); 12/** 13 * sort String arrays 14 * @ param keys15 * @ return16 **/17 public static String [] getUrlParam (String [] keys) {18 19 for (int I = 0; I <Keys. length-1; I ++) {20 for (int j = 0; j <keys. length-I-1; j ++) {21 String pre = keys [j]; 22 String next = keys [j + 1]; 23 if (isMoreThan (pre, next) {24 String temp = pre; 25 keys [j] = next; 26 keys [j + 1] = temp; 27} 28} 29} 30 return keys; 31} 32 33/** 34 * compares the size of two strings, compare 35 * @ param pre36 * @ param next37 * @ return38 **/39 private static boolean isMoreThan (String pre, String next) {40 if (Null = pre | null = next | "". equals (pre) | "". equals (next) {41 _ log. error ("string comparison data cannot be blank! "); 42 return false; 43} 44 45 char [] c_pre = pre. toCharArray (); 46 char [] c_next = next. toCharArray (); 47 48 int minSize = Math. min (c_pre.length, c_next.length); 49 50 for (int I = 0; I <minSize; I ++) {51 if (int) c_pre [I]> (int) c_next [I]) {52 return true; 53} else if (int) c_pre [I] <(int) c_next [I]) {54 return false; 55} 56} 57 if (c_pre.length> c_next.length) {58 return true; 59} 60 61 return false; 62} 63 64 65 public static void main (String [] args) {66 67 String [] keys = getUrlParam (new String [] {"fin", "abc", "shidema", "shide", "bushi "}); 68 69 for (String key: keys) {70 System. out. println (key); 71} 72 73} 74}
The result is as follows:
Abc
Bushi
Fin
Shide
Shidema