gpt4 book ai didi

java - 辅助方法: Doubling Chars in a String but stops recursion after first char

转载 作者:行者123 更新时间:2023-12-01 16:44:12 26 4
gpt4 key购买 nike

这是我陷入困境的家庭作业。我给出一个 ArrayList,我需要返回一个所有字符都加倍的字符串。输入:abc,输出:aabbcc。我得到的输出是 aa,然后就停止了。我已经用循环完成了多次,但似乎无法通过递归得到它。

我尝试重新编辑我的代码,并尝试使用计数器,但我要么得到空返回,要么得到溢出流错误。我访问 Oracles 网站找出可以使用的其他 String 方法,并尝试使用其他方法更改我的代码,但仍然没有成功。

我的其他方法可以将 ArrayList 转换为字符串,但这是我遇到问题的最后一个方法。

public String dupEachChar2(String str) {
//str is going to be a string with abc in it.
String x = "";
int count = 0;

// I'm checking if there is only 1 char, if so just return it twice to 1 string.
if(str.length() == 1) {
return str + str;
} else if(count != str.length()) {
//Doubling part that I can not figure out.
x += str.substring(count, count+1) + str.substring(count, count+1);
count++;
dupEachChar2(str.substring(count));
}
return x;
}

最佳答案

您可以使用 String.replaceAll() 的反向引用功能。要将字符串中的每个字符替换为重复字符,请执行以下操作:

String a = "abc";
String b = a.replaceAll("(.)", "$1$1");
b is now equals to aabbcc

这是它的工作原理。

  • . 表示匹配任何字符,() 是正则表达式的组捕获。
  • $1 表示获取第一组(即#1)中匹配的内容。然后只需使用它两次即可将角色加倍。

关于java - 辅助方法: Doubling Chars in a String but stops recursion after first char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55997490/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com