你好
我正在尝试编写一个递归函数来计算 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)
最佳答案
Java 字符串不是 C 字符串。字符串在其长度中的字符数之后结束。
关于java - 字符串如何在java中终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3974398/