簡體   English   中英

反轉字符串中的所有字符

[英]Invert all characters in a string

我想反轉字符串的每個字符並在 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]

假設您想要獲得像[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;
}

您應該將緩沖區重置為原始狀態:

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
 ^^     ^^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM