如何通过递归实现首尾交替拼接的字符串?Java代码报错求助
问题:修正递归字符串处理函数解决索引越界并实现需求
需求说明
递归函数接收一个字符串,返回一个新字符串,新字符串的每一组字符由原字符串的首字符和尾字符依次组成。示例:
- 接收:
abcde,返回:aebdc - 接收:
1a2b3c,返回:1ca32b
原代码及问题
原代码运行时抛出String index out of range: 0异常:
public class Ex_6 { public static void main(String[] args) { String str= "1a2b3c";// 1c a3 2b System.out.println(insideOut(str)); } public static String insideOut(String str) { char ch= str.charAt(0); String newStr = ""; if (str.length()==1 || str.length()==0 ) //基准情况(输入单个字符时返回自身) newStr= str; else //尝试构造新字符串 newStr= ch+str.charAt(str.length()-1) + insideOut(str.substring(1, str.length()-1)); return newStr; //运行报错:"String index out of range: 0" } }
问题原因
代码中char ch= str.charAt(0);放在了基准判断之前,当递归到空字符串时(比如处理长度为2的字符串时,递归调用insideOut(str.substring(1,1))会得到空字符串),调用charAt(0)会直接触发索引越界,因为空字符串没有索引0的字符。
修正后的代码
public class Ex_6 { public static void main(String[] args) { String str= "1a2b3c";// 1c a3 2b System.out.println(insideOut(str)); // 测试边界情况 System.out.println(insideOut("")); System.out.println(insideOut("x")); System.out.println(insideOut("abcde")); } public static String insideOut(String str) { String newStr = ""; // 先处理空字符串,避免索引访问 if (str.length() == 0) { newStr = str; } else if (str.length() == 1) { // 单个字符直接返回自身 newStr = str; } else { // 仅当字符串长度大于1时,才获取首尾字符 char firstChar = str.charAt(0); char lastChar = str.charAt(str.length() - 1); // 递归拼接中间子串的处理结果 newStr = firstChar + String.valueOf(lastChar) + insideOut(str.substring(1, str.length() - 1)); } return newStr; } }
修正要点
- 调整字符获取位置:将首尾字符的获取逻辑移到
else分支内,只有当字符串长度大于1时才执行,避免空字符串或单字符时触发索引越界。 - 拆分基准判断:先判断空字符串,再判断单字符,逻辑更清晰,确保边界情况被优先处理。
- 补充测试用例:添加空字符串、单字符及示例字符串的测试,验证所有场景的正确性。
内容的提问来源于stack exchange,提问作者Mirel
相关产品推荐
相关产品推荐

