Sort a single String in Java

后端 未结 10 939
误落风尘
误落风尘 2020-11-28 18:15

Is there a native way to sort a String by its contents in java? E.g.

String s = \"edcba\"  ->  \"abcde\"
10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 18:33

    public static void main(String[] args) {
        String str = "helloword";   
        char[] arr;
        List l = new ArrayList();
        for (int i = 0; i < str.length(); i++) {
            arr = str.toCharArray();
            l.add(arr[i]);
    
        }
        Collections.sort(l);
        str = l.toString();
        System.out.println(str);
        str = str.replaceAll("\\[", "").replaceAll("\\]", "")
                .replaceAll("[,]", "");
        System.out.println(str);
    
    }
    

提交回复
热议问题