天天看点

Java对字符串中字符进行按自然顺序排序

@Test
public void show(){
String s1 = "qwertyasdfghzxcvbn";
String s2 = myStrSort(s1);
System.out.println(s2); //=> abcdefghnqrstvwxyz
}
public String myStrSort(String s){
// 先将字符传转为 char 型数组
char[] chars = s.toCharArray();
// 使用 Arrays.sort(chars) 方法进行排序
Arrays.sort(chars);
// 然后再将char型数组作为参数传递给String类构造器
String sortStr = new String(chars);
// 返回排序好的字符串
return sortStr;
}