【问题标题】:remove and add char to string recursion删除字符并将其添加到字符串递归
【发布时间】:2018-05-27 07:17:23
【问题描述】:

如何在最后的递归中制作char 或示例:

removeChar ("hello world, let's go!",'l') → "heo word, et's go!llll"

removeChar("you should not go",'o') → "yu shuld nt goooo"

public static String removeChar(String word, char charToRemove) {
  String char_toremove = Character.toString(charToRemove);
  for (int i = 0; i < word.length(); i++) {
    if (word.charAt(i) == charToRemove) {
      String newWord = word.substring(0, i) + word.substring(i + 1);
      return removeChar(newWord, charToRemove);
    }
  }
  System.out.println(word);
  return word;
}

【问题讨论】:

标签: java string recursion char


【解决方案1】:

假设你打电话给removeChar("hello ", 'l')
您目前删除了l,
递归调用removeChar("helo ", 'l'),
然后直接返回。

首先,这不是最佳选择,因为它现在必须扫描已被扫描的初始 he 字符。

其次,不要直接退货。在返回递归调用的结果之前,将删除的字母添加到末尾。

所以,而不是:

String newWord = word.substring(0, i) + word.substring(i + 1);
return removeChar(newWord, charToRemove);

你想要:

String prefix = word.substring(0, i);
String remain = word.substring(i + 1);
String subst = removeChar(remain, charToRemove);
return prefix + subst + charToRemove;

或者只是一行:

return word.substring(0, i) + removeChar(word.substring(i + 1), charToRemove) + charToRemove;

【讨论】:

  • 感谢您的回复,它返回“o”表示“hello,'l' 而不是“heoll”,您知道为什么吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
  • 2013-02-05
  • 1970-01-01
  • 2019-08-30
  • 2015-09-24
  • 2019-06-26
相关资源
最近更新 更多