You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串反转输入输出异常问题:输入'pli'得到'ili'的原因排查

Why Aren't the First and Last Elements Swapping Correctly in My String Reverse Code?

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] → now input[0] becomes 'i', so your array is now ['i','l','i']
  • input[2] = input[0] → here you're assigning the already changed input[0] (which is 'i') to input[2], instead of using the original 'p' you stored in temp. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 08:57:34