简体   繁体   English

计算字符串中空格和句点数的递归方法

[英]Recursive method that counts the number of spaces and periods in a string

I'm having a bit of trouble trying to create a recursive method that counts the number of periods and spaces in a string.我在尝试创建一个递归方法来计算字符串中的句点和空格数时遇到了一些麻烦。 I can do this pretty easily using iteration, but I'm still fairly new to the concept of recursion.我可以使用迭代很容易地做到这一点,但我对递归的概念仍然相当陌生。 Here's my code so far, could anyone tell me where I'm going wrong?到目前为止,这是我的代码,谁能告诉我哪里出错了?

public static int periodsAndSpaces(String s){ //option 3
    if(s.length()<0){ //base case
        return 0;
    }

    else if(s.charAt(0) == ' ' || s.charAt(0) == '.'){ //general case
        return periodsAndSpaces(s.substring(1)) + 1;
    }
    return 0;
}
package com.test.demo;

public class Counter {

    public static void main(String[] args) {
        System.out.println(new Counter().countPeriodsAndSpaces(" test. . .a"));
    }

    int countPeriodsAndSpaces(String rs) {
        if (rs == null || rs.isEmpty()) 
            return 0;
        
        char c = rs.charAt(0);
        if (c == ' ' || c == '.') 
            return 1 + countPeriodsAndSpaces(rs.substring(1)); 
        else 
            return countPeriodsAndSpaces(rs.substring(1)); 
    }
    
}

// Output 6 // 输出 6

New method with everyone's suggestions:大家建议的新方法:

public static int periodsAndSpaces(String s){ //option 3
    if(s.length()==0){ //base case
        return 0;
    }

    else if(s.charAt(0) == ' ' || s.charAt(0) == '.'){ 
        return periodsAndSpaces(s.substring(1)) + 1;
    }
    else{
        return periodsAndSpaces(s.substring(1));
    }
}

Method stops running when there are no more characters left in the string, and I've added another case for adding onto the sum of periods and spaces when the current char doesn't have either of these.当字符串中没有更多字符时,方法将停止运行,并且我添加了另一种情况,用于在当前字符中没有任何一个时添加句点和空格的总和。

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

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