If you compare the size of two strings directly, it will include: The operator > is undefined for the argument type(s) java.lang.String, java.lang.String error.
The string size can be compared with the string length or the ASCII code value of the characters in the string. The former is too simple, so the narration will not be recorded.
The strings are compared with ASCII code, and the rules are:
1. Compare the ASCII code sizes of the first letter
2. If the letters in the previous are the same, then the ASCII code values of the letters after comparison
3. If a string contains another string from the first letter, it is considered that the string has a longer length; example: abc > ab
Note: Use commons-logging-1.2.jar in the code, sorting from small to large
import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;/** * Sort string array* @author panjianghong * @since 2016/8/31 * */public class StringSort { private static final Log _log = LogFactory.getLog(StringSort.class); /** * Sort string array* @param keys * @return * */ public static String[] getUrlParam(String[] keys){ for (int i = 0; i < keys.length - 1; i++) { for (int j = 0; j < keys.length - i -1; j++) { String pre = keys[j]; String next = keys[j + 1]; if(isMoreThan(pre, next)){ String temp = pre; keys[j] = next; keys[j+1] = temp; } } } return keys; } /** * Compare the sizes of two strings and compare according to the ASCII code of letters* @param pre * @param next * @return * */ private static boolean isMoreThan(String pre, String next){ if(null == pre || null == next || "".equals(pre) || "".equals(next)){ _log.error("String comparison data cannot be empty!"); return false; } char[] c_pre = pre.toCharArray(); char[] c_next = next.toCharArray(); int minSize = Math.min(c_pre.length, c_next.length); for (int i = 0; i < minSize; i++) { if((int)c_pre[i] > (int)c_next[i]){ return true; }else if((int)c_pre[i] < (int)c_next[i]){ return false; } } if(c_pre.length > c_next.length){ return true; } return false; } public static void main(String[] args) { String[] keys = getUrlParam(new String[]{"fin","abc","shidema","shide","bushi"}); for (String key : keys) { System.out.println(key); } }}The console print result is:
abc
bushi
fin
Shide
Shidema
The simple implementation of java string array size sorting is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.