在Java中递归删除字符

gry*_*ryb 2 java methods recursion character

作为练习,下面的代码块打算递归地遍历一个字符串并删除所有的"x"字符.它这样做,但我想跟踪newStr而不将其作为方法中的参数传递.无论如何将它移动到方法体中?

谢谢!

public static String deathToX(String str, String newStr) {  
    //look for x char
    if(str.substring(0, 1).equals("x")) {
        //do nothing
    } else {
        //add non-x char to newStr
        newStr += str.charAt(0);
    }

    if(str.length() == 1) {
        return newStr;
    }

    return deathToX(str.substring(1), newStr);
}

public static void main(String[] args) {
    System.out.println("Return: " + deathToX("xnoxmore", ""));
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

好吧,您可以将代码更改为:

public static String deathToX(String str)
{   
    // Termination case
    if (str.length() == 0)
    {
        return str;
    }
    // Work out whether or not we want the first character
    String prefix = str.startsWith("x") ? "" : str.substring(0, 1);

    // Let the recursive call handle the rest of the string, and return
    // the prefix (empty string or the first character) followed by the
    // x-stripped remainder.
    return prefix + deathToX(str.substring(1));
}
Run Code Online (Sandbox Code Playgroud)

那是你想到的那种事吗?

当然,这是一种非常低效的字符串操作方式,但我认为你对事物的递归本质更感兴趣.