方法一:
public static String sort1(String str) {
byte[] bytes = str.getBytes();
// Arrays类里面的sort()方法
Arrays.sort(bytes);
return new String(bytes);
}
方法二:
public static String sort2(String str) {
// 1、把字符串转为字节数组
byte[] bytes = str.getBytes();
byte temp = 0; // 临时变量
// 比较的轮数(轮数 = 数组长度 - 1)
for(int i = 0;i < bytes.length - 1;i++) {
// 3、每轮比较的次数(每轮比较的次数 = 数组长度 - 1 - 轮数)
for(int j = 0;j < bytes.length - 1 - i;j++) {
// 4、判断当前的值是否比后面的大,大的话就进行交换
if(bytes[j] > bytes[j + 1]) {
temp = bytes[j];
bytes[j] = bytes[j + 1];
bytes[j + 1] = temp;
}
}
}
return new String(bytes);
}
方法三:
public static String sort3(String str) {
char[] chars = str.toCharArray();
// Arrays类里面的sort()方法
Arrays.sort(chars);
return new String(chars);
}
方法四:
public static String sort4(String str) {
// 1、把字符串转为字符数组
char[] chars = str.toCharArray();
char temp; // 临时变量
// 2、轮数(轮数 = 数组长度 - 1)
for(int i = 0;i < chars.length - 1;i++) {
// 3、比较次数(比较次数 = 数组长度 - 1 - 轮数)
for(int j = 0;j < chars.length - 1 - i;j++) {
// 4、判断当前的值是否比后面的大,大的话就进行交换
if(chars[j] > chars[j + 1]) {
temp = chars[j];
chars[j] = chars[j + 1];
chars[j + 1] = temp;
}
}
}
return new String(chars);
}