
Java 中 for 循环遍历字符串时,若错误使用 ijava 中 `for` 循环遍历字符串时,若错误使用 `i
在实现简易凯撒式字符偏移加密(如 BasicEncrypt.encrypt)时,一个常见却隐蔽的 bug 是:循环始终漏掉字符串的最后一个字符。根本原因在于循环终止条件写成了:
for (i = 0; i <p>该条件使 i 最大仅达 text.length() - 2,导致索引 text.length() - 1(即最后一个有效字符位置)从未被访问。例如,对字符串 "a"(长度为 1),i </p><p>✅ 正确的循环结构应为:</p><pre class="brush:php;toolbar:false;">for (int i = 0; i <p>但仅修正循环条件还不够。原代码中还存在<strong>逻辑混淆与类型错误</strong>:</p>
❌ 错误写法:code = code + text.charAt(i + rule)
→ i + rule 极易越界(如 i=5, rule=3 时访问 text[8],而字符串可能只有 6 个字符),引发 StringIndexOutOfBoundsException。❌ 类型陷阱:code = code + text.charAt(i) + rule
→ 由于 + 的左结合性,此表达式等价于 (code + text.charAt(i)) + rule,即先拼接字符(转为字符串),再拼接数字(如 "a" + 1 → "a1"),并非预期的字符偏移。✅ 正确做法是:先计算偏移后的整数值,再强制转为 char,并统一处理溢出(模 256 更合理,但题目限定用 255):
public static String encrypt(String text, int rule) { if (text == null) return null; StringBuilder code = new StringBuilder(); // 推荐用 StringBuilder 替代字符串拼接 for (int i = 0; i 255) { code.append((char) (shifted - 255)); } else { code.append((char) shifted); } } return code.toString(); }? 关键注意事项:
- ✅ 始终用 text.charAt(i) 获取当前字符,绝不使用 text.charAt(i + rule);
- ✅ 字符偏移运算应在 int 上进行,结果显式转为 char;
- ✅ 使用 StringBuilder 提升多次拼接性能(尤其长字符串);
- ⚠️ 当前逻辑按字节值(0–255)截断,若需可逆加密,建议改用模 256:(ch + rule) % 256;
- ? 生产环境应校验 rule 范围,避免过大偏移导致不可控行为。
通过以上修正,encrypt("abcdef", 1) 将正确输出 "bcdefg",encrypt("a", 1) 输出 "b",彻底解决末字符丢失问题。










