【发布时间】:2018-12-23 11:31:27
【问题描述】:
这个问题不言自明...设计一个名为 startChar(String str, char c) 的方法。这是我在这里找到的代码,但它在字符串的末尾插入了字符。我不知道递归地思考。我理解这段代码,但对它的理解不足以操纵它在开头放置字符。任何形式的帮助表示赞赏。
示例输入:
startChar("Apple",'p')
输出:
ppale
代码
public static String chrToLast(String str, char ch) {
//This if statement details the end condition
if(str.length() < 1) {
return "";
}
String newString = str.substring(1); //Create new string without first
character
if(str.indexOf(ch) == 0) { //This happens when your character is found
return chrToLast(newString, ch) + ch;
} else { //This happens with all other characters
return str.charAt(0) + chrToLast(newString, ch);
}
}
【问题讨论】:
-
我不明白这段代码的用途;你能提供更多的例子吗? 为什么输出是
"ppale"? -
我希望它返回
Alepp。将角色的所有实例移动到最后的想法不是吗?所以p字符都从原来的位置出来,走到了最后。 -
哦,我明白了。您想反转它以便将字符移动到开头而不是结尾?所以预期的输出应该是
ppAle,对吧? -
是的!例如考虑输入:(banana, a) 那么输出应该是 aaabnn。取所有 a's ,删除它们并将它们放在字符串的开头。
-
请将所有解释和示例添加到帖子中,而不是作为 cmets。
标签: java string recursion methods char