Hi
I am trying to write a recursive function which calculates the length of string in Java
I know that there already exists str.length() function, but the problem statement wants to implement a recursive function
In C programming language the termination character is '', I just want to know how to know if string ends in Java
My program ends well when I put '
' in the test string. Please let me know. Thanks!
/*
* 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
";
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) == '
'){
return 0;
}
i += 1;
return 1 + strlen(str);
}
}
Output :
run:
len : 7
BUILD SUCCESSFUL (total time: 0 seconds)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…