字符串如何在Java中终止?

做白日梦的人:

嗨,
我正在尝试编写一个递归函数来计算Java中字符串的长度,
我知道已经存在str.length()函数,但是问题语句想要实现一个递归函数

在C编程语言中,终止字符为'\ 0',我只想知道如何知道字符串是否以Java结尾

当我在测试字符串中输入“ \ n”时,我的程序运行良好。请告诉我。谢谢!

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package careercup.google;

/**
 *
 * @author learner
 */
public class Strlen {
    private static final String Test = "abcdefg\n";
    private static int i =0;

    public static void main(String args[]){
        System.out.println("len : " + strlen(Test));
    }

    private static int strlen(String str){
        if(str == null){
            return 0;
        }
        if(str.charAt(i) == '\n'){
            return 0;
        }
        i += 1;
        return 1 + strlen(str);
    }
}

输出:

run:
len : 7
BUILD SUCCESSFUL (total time: 0 seconds)
乌普尔机场:

请记住,此代码效率很低,但是它以递归方式计算String的长度。

private static int stringLength(String string){
        if(string == null){
            return 0;
        }

        if(string.isEmpty()){
            return 0;
        }

        return 1 + stringLength(string.substring(1));
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章