You need to enable JavaScript to run this app. Java实现字符串非空格字符前插入字符p 解决空格误插与数组越界问题
优惠活动
大模型
产品
解决方案
定价
更多

Java实现字符串非空格字符前插入字符p 解决空格误插与数组越界问题

pEncrypt方法实现存在的问题
  • 当前编写的pEncrypt方法可实现基础的前置插'p'逻辑,但存在效果偏差
  • 偏差复现场景:输入字符串I like bananas时,输出结果为pIp ppipkpep pbpapnpapnpaps
  • 预期实现规则:为每个非空格字符前置插入指定字符'p',空格前不插入,最终得到pI pLpipkpe pbpapnpapnpaps

修复尝试遇到的阻碍

已尝试的所有解决方案都需要通过if语句判断原输入字符串encText对应位置的字符是否为空格:若为空格则在newText数组的对应位置直接赋值为空格,无需额外插入前置'p';否则再按规则处理,但每次尝试都会触发数组越界异常。

当前运行的代码片段

static void pEncrypt() {
    System.out.println("Adding P");
    Scanner in = new Scanner(System.in);
    String encText = in.nextLine();
    int k = encText.length();

    char[] charsEncText = encText.toCharArray();
    char[] newText = new char[2 * k];

    int j = 1;

    for (int i = 0; i < (k * 2); i++) {
        if (i % 2 == 0) {
            newText[i] = 'p';
        } else {
            newText[i] = charsEncText[i - j];
            j++;
        }
    }
    System.out.println(newText);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 17:36:04