我的程序需要从用户读取一个字符串和两个索引值,然后用指定的索引值交换字符,并将结果字符串保存在变量中。 现在我所能做的就是交换用户输入字符串的2个首字母,我无法弄清楚如何从用户交换2个索引值
答案 0 :(得分:1)
使用String.toCharArray()
将输入转换为char[]
。然后,您可以使用索引并交换所需的字符。然后,您只需要从数组中构造一个新字符串。请参阅String javadocs。
答案 1 :(得分: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
}