如何在 Java 中不使用預定義的方法對字串進行排序?
字串是一個物件,表示一個不可變的字元序列,一旦建立就無法更改。java.lang.String 類可用於建立一個字串物件。
在下面的程式中,我們可以在不使用 Java 中 String 類的任何預定義方法的情況下對字串的字元進行排序。
示例
public class SortStringWithoutPredefinedMethodsTest { public static void main(String[] args) { String str = "jdkoepacmbtr"; System.out.println("Before Sorting:" + str); int j = 0; char temp = 0; char[] chars = str.toCharArray(); for(int i=0; i < chars.length; i++) { for(j=0; j < chars.length; j++) { if(chars[j] > chars[i]) { temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } } } System.out.println("After Sorting:"); for(int k=0; k < chars.length; k++) { System.out.println(chars[k]); } } }
輸出
Before Sorting:jdkoepacmbtr After Sorting: a b c d e j k m o p r t
廣告