2015-10-05 23 views
0

我的程序需要從用戶讀取一個字符串和兩個索引值,然後將字符與指定索引值交換,並將結果字符串保存在變量中。 現在我所能做的就是交換用戶輸入字符串的2個字母,我無法弄清楚如何從用戶讀取一個字符串和2個索引變量,然後交換指定索引中的那些字符

+4

那麼,你如何交換前兩個字母?一點代碼會有幫助。 – RealSkeptic

+4

您是否嘗試編寫任何代碼? – MaxZoom

回答

1

使用String.toCharArray()交換2個索引值的輸入轉換爲char[]。然後,您可以使用索引並交換所需的字符。然後你需要的是從數組中構造一個新的字符串。請參閱String javadocs。

0

假設您有原始的String和兩個索引,您可以像這樣交換字符。

public static String swapChars(String word, int firstIndex, int secondIndex) { 
    if (Math.min(firstIndex, secondIndex) < 0 || Math.max(firstIndex, secondIndex) > word.length() - 1) { // If either of the indices are negative or too large, throw an exception 
     throw new IllegalArgumentException("Indices out of bounds!"); 
    } 
    if (firstIndex == secondIndex) { // If they are equal we can return the original string/word 
     return word; 
    } 
    char[] characters = word.toCharArray(); // Make a char array from the string 
    char first = characters[firstIndex]; // Store the character at the first index 
    characters[firstIndex] = characters[secondIndex]; // Change the character at the first index 
    characters[secondIndex] = first; // Change the character at the second index using the stored character 
    return new String(characters); // Return a newly built string with the char array 
} 
+1

你在哪裏檢查索引邊界? – MaxZoom

+0

已添加,因爲您提出要求! :)對字符串進行空檢查可能也是必要的,但我會將其留給提出問題的用戶。 –

相關問題