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

Java实现字符数组前N元素移至末尾及单词移位问题排查

问题分析与修复

你处理奇数长度单词时的核心问题是误用了字符交换逻辑,这和“将前半部分+1长度的字符移至末尾”的需求不匹配——原代码的交换操作只是调换了部分字符位置,而非将指定前缀整体移到单词末尾。

修复思路

直接用Java的substring方法实现字符段移动,逻辑更直观且不易出错:

  • 偶数长度:取后半段字符串拼接前半段字符串
  • 奇数长度:取从(长度//2 +1)位开始的后半段,拼接前(长度//2 +1)位的前缀

修正后的代码

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class Exercise5 {

    public static void main(String[] args) throws IOException {
        FileInputStream inputFile = new FileInputStream("input.in");
        Scanner scnr = new Scanner(inputFile);
        String sentence = scnr.nextLine();
        String[] inputSentence = sentence.split(" ");

        for (String word : inputSentence) {
            String result;
            int len = word.length();
            if (len % 2 == 0) {
                // 偶数长度:后半段 + 前半段
                result = word.substring(len / 2) + word.substring(0, len / 2);
            } else {
                // 奇数长度:后半段(从len//2+1开始) + 前(len//2+1)位的前缀
                int splitPos = len / 2 + 1;
                result = word.substring(splitPos) + word.substring(0, splitPos);
            }
            System.out.println(result);
        }
        // 关闭资源
        scnr.close();
        inputFile.close();
    }
}

测试示例

  • 输入the(长度3,奇数):拆分位置为2,结果为eth
  • 输入wonderful(长度9,奇数):拆分位置为5,结果为rfulwonde
  • 输入test(长度4,偶数):结果为stte,符合需求

内容的提问来源于stack exchange,提问作者Haplo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:12:38