一、最近做项目需要对多个字符串进行ASCII从小到大排序加密,写个随笔记录下学习,代码如下:
/** * 字符串工具类 * @author skyhcwwu */ public class StringUtil { public static void main(String[] args) { System.err.println(" --------------------------------------------------------------------------------------------------- "); String[] source1 = new String[]{"demo", "about", "count", "resolove02", "resolove01", "aboutting", "basic", "abist"}; System.err.println("排序前String[]: " + converToString(source1)); System.err.println(); // 排序 sortString(source1); System.err.println("排序后String[]: " + converToString(source1)); } /** * 对传入的字符串数组进行ASCII排序 * @param source 字符串数组 * @return */ public static String[] sortString(String[] source) { String str1 = ""; String str2 = ""; String temp = ""; int length = 0; for (int i = 0; i < source.length; i++) { for (int m = 0; m < source.length - 1; m++) { str1 = source[m]; str2 = source[m + 1]; length = str1.length() > str2.length() ? str2.length() : str1.length(); for (int j = 0; j < length; j++) { if (str1.charAt(j) == str2.charAt(j)) { continue; }else if (str1.charAt(j) < str2.charAt(j)) { break; } else { temp = str1; source[m] = str2; source[m + 1] = temp; } } } } return source; } public static String converToString(String[] source) { StringBuffer sb = new StringBuffer(); String str1 = ""; for (int k = 0; k < source.length; k++) { str1 = source[k]; if (k != source.length -1 ) { sb.append(str1).append(", "); } else { sb.append(str1); } } return sb.toString(); } }
二、执行main方法后得到的结果: