试图递归计算字符串中的空格? [英] Trying to count blank spaces in a string recursively?

查看:154
本文介绍了试图递归计算字符串中的空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真的很抱歉,我的意思是Java!至于我的想法,我会说第一个包含if语句是s == null或长度为0的,但是我对于放在

Really sorry, I mean Java! As for what I think, I would say the first contains if statement is for s == null or length 0, but I'm confused as to what to put in the

返回spaceCount(s.substring(1,......))+ ......;

return spaceCount(s.substring(1, ......)) + ......;

部分.

我正在尝试使用一些if语句编写一个将字符串作为参数并递归的函数,该函数包含空格.到目前为止,我有

I'm trying to use some if statements to write a function that takes a string as a parameter and recursively coutns the number of blanks spaces " " it has. So far I have

public static int spaceCount (string s) {
    if ( ...... ) {
        return 0;
    }
    char c = s.charAt(0);
    if (....... ) {
        return spaceCount (.....);
    } else {
        return spaceCount(s.substring(1, ......)) + ......;
    }
}

所以在第一个if语句中,我应该写长度为零的字符串的情况吗?我很确定这根本不会涵盖没有空格的情况,因此我不确定如何继续.

So in the first if statement, should I write the case of the string having zero length? I'm pretty sure that won't cover the case of no spaces at all, so I'm not sure how to proceed.

对于第二和第三,我知道我必须扫描字符串中的空格,但是我也不十分确定该怎么做.任何提示或指示,将不胜感激!

For the second and third, I know I have to scan the string for spaces, but I am not really sure how to do that either. Any hints or direction would be appreciated!

推荐答案

public static int spaceCount(final String s) {

    if(s == null || s.length() == 0) {
        return 0;
    }

    char c = s.charAt(0);
    if(' ' != c) {
        return spaceCount(s.substring(1));
    } else {
        return spaceCount(s.substring(1)) + 1;
    }

}

您不必扫描字符串中的空格",这就是传递字符串其余部分的递归.

You don't have to "scan the string for spaces", that's what the recursion passing the remainder of the string does.

这篇关于试图递归计算字符串中的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆