2017-07-01 41 views
2

在下面的代碼中,我試圖將i中的char與i + 1中的char進行比較。我的理解是,通過使用charAt():我可以從字符串中取出字符並將其視爲整數並能夠比較兩個字符。代碼的這部分工作,但我認爲我錯過了代碼中的某些東西,因此它不打印所需的結果。除非這種對字符串中的字符進行排序的方式無效。有沒有一種方法來按字母順序對字符串進行排序而不將字符串放入數組中?

public class stringAlphabetical { 

    public static void main(String[] args){ 
     String word="watch"; 
     boolean swapped; 
     char temp = ' '; 
     do{ 
      swapped = false; 
      for(int i=0;i<word.length()-1;i++){ 
       char a = word.charAt(i); 
       char b = word.charAt(i+1); 

       if(word.charAt(i)>word.charAt(i+1)){ // if (a>b) { 
        temp = a; 
        a = b; 
        b = temp; 
       } 
      } 


     }while (swapped==true); 

     System.out.println(word); 
    } 
} 
+0

什麼是您避免陣列存儲的目的?使用可變數據結構(如數組或List)是執行排序等操作的有效方法。 – dimo414

+0

另外,你永遠不會更新'word'的值,所以這段代碼只是再次打印原始輸入。 – dimo414

回答

2

的Java String不變,所以你需要使用一個可變類(如StringBuilder) - (也,你正在修改char值,不是引用),你不需要t

StringBuilder word = new StringBuilder("watch"); 
boolean swapped; 
do { 
    swapped = false; 
    for (int i = 0; i < word.length() - 1; i++) { 
     char a = word.charAt(i), b = word.charAt(i + 1); 

     if (a > b) { // <-- this is fine. 
      word.setCharAt(i, b); 
      word.setCharAt(i + 1, a); 
      swapped = true; 
     } 
    } 
} while (swapped); 
System.out.println(word); 

,輸出

atchw 

或者只是使用一個數組(相同的結果)

String word = "watch"; 
char[] c = word.toCharArray(); 
Arrays.sort(c); 
System.out.println(new String(c)); 
1

按字母順序排序的字符串,則需要每個字符的所有字符比較如果條件滿足,那麼你交換角色。 這是使用多個循環顯示的。最後我打印字符數組。

public static void main(String[] args){ 
     String watchString = "watch"; 
     int j; 
     char temp; 

     char[] chars = watchString.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; 
       } 

      } 

     } 

     for(int k=0;k<chars.length;k++){ 
      System.out.print(chars[k]); 
     } 

    } 
1

使用此代碼,通過排序按字母順序排列的String數組沒有任何陣列

Scanner kbd = new Scanner(System.in); 
    String input = kbd.nextLine(); 
    String sortedString = Stream.of(input.split("")).sorted().collect(Collectors.joining()); 
    System.out.print(sortedString); 
相關問題