繁体   English   中英

递归方法如何计算字符串中的空格?

[英]How does recursive method to count white spaces in a string work?

我试图全面了解该方法的工作原理,请参见下面的代码:

public static void main(String[] args) {
    System.out.println(countspaces("a number of spaces "));
}

public static int countspaces(String s) {
    if (s.length() == 0)
        return 0;
    else
        return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
}

我已经使用BlueJ调试了该方法。 该行:

return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));

首先检查索引为零的字符是否为空格,然后再次调用自身(这使其递归),以从索引1开始的s的子字符串作为参数,从而有效地将参数从“多个空格”更改为“直到参数的length()达到0为止。我不明白的是为什么它不返回01000000100100000010(最后一个0是用于终止循环的空字符串s)而是4? 我看不到它在代码中的总和由1返回

(s.charAt(0) == ' ' ? 1 : 0)

并忽略0。 请告诉我我的推理中缺少的内容。

非常感谢

格热哥兹(格雷格)

(s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1))

这个基本上将0 s和1 s相加。

注意该方法的返回值int 返回值4非常好。

换句话说:

0 + 1 + 0 + 0 + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 = 4

由于该方法返回的是int而不是字符串,因此它会添加数字,而不是串联为字符/字符串。

0+1+0+0+0+0+0+0+1+0+0+1+0+0+0+0+0+0+1+0 == 4

"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"+"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0" 
== "01000000100100000010"

下面返回一个int,因为countspaces返回一个int

return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));

为了帮助您理解它,请尝试用“英语”编写该函数:

int countspaces( string ) {

    if string has no characters {
        return 0
    }
    else {

        if first character in string is a space 

        add 1 

        otherwise

        add 0

        to result of countspaces( string_with_first_character_removed )
    }
}

递归的点是该函数被一遍又一遍地调用,您可以粗略地说这是某种循环。

if (s.length() == 0)
    return 0;

这段代码是递归函数的停止条件(因为递归此时已停止),当提供的字符串的长度为0时,它将返回0。这里没有什么要解释的,我认为这很明显。

这部分是递归函数的核心部分:

return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));

s.charAt(0) == ' ' ? 1 : 0 s.charAt(0) == ' ' ? 1 : 0使用三元运算符 ,它检查字符串中的第一个字符是否为空格,如果为true,则使用值1,否则使用0。

countspaces(s.substring(1))再次调用该函数,并且子字符串会删除第一个字符。

函数返回的int值为0或1,它对返回的值进行求和,如您所知, x + 0 = x ,所以只有第一个字符为空格(函数返回1)的情况才会影响最终结果。

调用将一直进行到函数传递自身的空字符串(达到停止条件)时 ,才返回调用堆栈,返回的值与三元运算符的值相加,最后返回预期的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM