字符串反转输入输出异常问题:输入'pli'得到'ili'的原因排查
Let's break down what's going wrong here step by step—you're really close, but two key issues are causing the messed-up output when reversing "pli":
1. Your swap logic is missing a critical step
Look at how you're trying to swap characters:
char temp = input[index]; input[index] = input[maxIndex - index]; input[maxIndex - index] = input[index];
You correctly save the original value of input[index] into temp, but you never actually use temp for the final assignment! Let's walk through the first iteration (when index = 0 and your input is ['p','l','i']):
temp = 'p'(this part is right—you're storing the first character)input[0] = input[2]→ nowinput[0]becomes 'i', so your array is now['i','l','i']input[2] = input[0]→ here you're assigning the already changedinput[0](which is 'i') toinput[2], instead of using the original 'p' you stored intemp. That's why the last character stays 'i' instead of turning into 'p'!
Fix this by using temp for the final swap step:
char temp = input[index]; input[index] = input[maxIndex - index]; input[maxIndex - index] = temp;
2. Your loop runs too many times
Right now your loop condition is index <= maxIndex, which means you'll end up swapping each pair twice. For a 3-character string, you loop 3 times (index 0, 1, 2):
- After fixing the swap logic, index 0 swaps positions 0 and 2 correctly →
['i','l','p'] - Index 1 swaps position 1 with itself (no problem, but unnecessary)
- Index 2 swaps positions 2 and 0 again → swapping them right back to the original
['p','l','i']!
You only need to loop up to the middle of the string to avoid re-swapping. Update your loop condition to:
for (int index = 0; index < maxIndex / 2; index++) {
For a length-3 string, maxIndex / 2 is 1, so the loop runs exactly once (index 0)—perfect, no extra swaps.
Corrected Full Code
Also, a quick reminder: Java Strings are immutable, so you can't modify individual characters directly unless you convert the String to a char[] first. Here's the fixed code in action:
public class ReverseString { public static void main(String[] args) { String original = "pli"; char[] input = original.toCharArray(); int maxIndex = input.length - 1; for (int index = 0; index < maxIndex / 2; index++) { char temp = input[index]; input[index] = input[maxIndex - index]; input[maxIndex - index] = temp; } String reversed = new String(input); System.out.println(reversed); // Outputs: ilp } }
内容的提问来源于stack exchange,提问作者Themeiscool

