2015-09-27 54 views
-2

我想顛倒我的字符串的每個字符並將每個結果返回給ArrayList。這是我的代碼:顛倒字符串中的所有字符

public static ArrayList<String> allInv(String word) { 
    ArrayList<String> ListMotsInverse = new ArrayList<String>(); 
    ListMotsInverse.add(word); 
    StringBuilder newWord = new StringBuilder(word); 
    for(int i = 0; i<word.length()-1; i++){ 
     char l = newWord.charAt(i);char r = newWord.charAt(i+1); 
     newWord.setCharAt(i, r); 
     newWord.setCharAt(i+1, l); 
     System.out.println(newWord); 
     ListMotsInverse.add(newWord.toString()); 
    } 
    return ListMotsInverse; 
} 

我的結果:

ArrayList<String> resInv = allInv("abc"); 
System.out.println(resInv); 
[abc, bac, bca] 

但我想這樣的結果:

[abc, bac, acb] 
+4

什麼使'[ABC,BAC,ACB]'優於'[ABC,BAC,BCA]'?我不知道你的意思是「逆」。 –

+1

我不明白OP想要什麼。 – user3437460

+0

我只想用i + 1切換string.charAt(i)。 – kakame91

回答

2

您應該將緩衝區重置爲初始狀態:

public static ArrayList<String> allInv(String word) { 
    ArrayList<String> ListMotsInverse = new ArrayList<String>(); 
    ListMotsInverse.add(word); 
    StringBuilder newWord = new StringBuilder(word); 
    for(int i = 0; i<word.length()-1; i++){ 
     char l = newWord.charAt(i);char r = newWord.charAt(i+1); 
     newWord.setCharAt(i, r); 
     newWord.setCharAt(i+1, l); 
     System.out.println(newWord); 
     ListMotsInverse.add(newWord.toString()); 

     //reset to original state 
     newWord.setCharAt(i, l); 
     newWord.setCharAt(i+1, r); 
    } 
    return ListMotsInverse; 
} 

在你的情況下,你將切換兩個字符:

abc -> bac 
^^  ^^ 

但沒有復位,所以它會做:

bac -> bca 
^^  ^^ 

,你希望:

abc -> acb 
^^  ^^ 
+1

好的工作!它的工作原理 – kakame91

4

假設你的意思是讓導致像簡單的方法[abc, bca, cab]一個實現這將創建另一個字符串,將複製原始字符串和子串的元素,你想要的:

abcabc 
^^^ 
^^^ 
    ^^^ 

public static List<String> allInv(String word) { 
    List<String> ListMotsInverse = new ArrayList<String>(); 
    String text = word+word; 
    for (int i=0; i<word.length(); i++){ 
     ListMotsInverse.add(text.substring(i,i+3)); 
    } 
    return ListMotsInverse; 
} 
+0

這是否會產生bac或acb ...? –

+1

@JaroslawPawlak它會返回'[abc,bca,cab]'。我可能是錯的,但我懷疑這可能是OP想要的。 – Pshemo

+0

同意你,我不知道,如果OP想交換字符或「滾動」字符串+1 @Pshemo – maskacovnik