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 '\0', I just want to know how to know if string ends in Java
My program ends well when I put '\n' 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\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);
}
}
Output :
run:
len : 7
BUILD SUCCESSFUL (total time: 0 seconds)