Java 在空白处递归添加星号

Java 在空白处递归添加星号,java,string,recursion,Java,String,Recursion,给定一个字符串,递归计算一个新字符串,其中所有相邻字符现在都用“*”分隔 例如: 全明星(“你好”)→ “*你好*在那里*” 这是我到目前为止的代码,但我认为我没有走上解决这个问题的正确道路 public static String allStar(String word) s = ""; if (word.equals(s)) { return null; } else if (word.charAt(0) == ' ') {

给定一个字符串,递归计算一个新字符串,其中所有相邻字符现在都用“*”分隔

例如: 全明星(“你好”)→ “*你好*在那里*”

这是我到目前为止的代码,但我认为我没有走上解决这个问题的正确道路

   public static String allStar(String word)


    s = "";

   if (word.equals(s))
   {
     return null;
   }


  else if (word.charAt(0) == ' ')
    {
    //Recursion should take place here
       return "*" + allStar(word.substring(1))


       //another recursive call, but I am not sure what to do!

     }

如果第一个
char
不是空格,请考虑您想要做什么。您不想修改它。获取子字符串中未修改的第一个字符,然后进行递归调用:

else {
    return word.substring(0, 1) + allStar(word.substring(1));
}

我建议你试试这样的东西;请注意,从您的条件开始停止递归是一个非常好的主意

public static String allStar(String word) {
  // null or the empty string, bail out (e.g. stop recursion).
  if (word == null || word.length() < 1) {
    return word;
  }
  // The first character.
  char c = word.charAt(0);
  if (c == ' ') {
    // replace a ' ' with a '*' and recurse.
    return "*" + allStar(word.substring(1));
  }
  // pass the character through and recurse.
  return c + allStar(word.substring(1));
}

// Demonstrate that it works.
public static void main(String[] args) {
  System.out.println(allStar(" hello there "));
}
公共静态字符串allStar(字符串字){
//null或空字符串,退出(例如停止递归)。
if(word==null | | word.length()<1){
返回词;
}
//第一个字符。
字符c=字字符(0);
如果(c=''){
//将“”替换为“*”并递归。
返回“*”+全明星(字子串(1));
}
//将字符传递并递归。
返回c+allStar(字子串(1));
}
//证明它是有效的。
公共静态void main(字符串[]args){
System.out.println(allStar(“你好”);
}

这里有一个简单的解决方案:)


请将代码的格式设置为符合某种形式的标准缩进/间距。这将使帮助您变得更容易。如果
word==”
,您应该返回
,而不是
null
。哦,对了!我的错误,谢谢。另外,别忘了括号
{}
和分号。我想基本情况已经处理好了(
word.equals(“”
)@iamnotmaynard,如果输入
word
null
,就会失败。我承认这可能是我想要的行为。是的,我不知道这是否应该是
null
-smart,或者在这种情况下NPE是否可以接受。我的观点是OP实际上是从停止条件开始的。谢谢大家的帮助。我很感激。谢谢你对你的代码发表评论,这样我就可以检查它并理解我的错误。@Henry,不客气!请
public String allStar(String str) {

  if(str.isEmpty()) return "";

  String sub = ((str.length()==1)?str.substring(0,1):str.substring(0,1) + "*");

  return sub + allStar(str.substring(1));


}