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)
Java strings are not C strings. The string ends after the number of characters in its length.
Please keep in mind that this code is very inefficient, but it calculates length of a String in recursive way.
private static int stringLength(String string){
if(string == null){
return 0;
}
if(string.isEmpty()){
return 0;
}
return 1 + stringLength(string.substring(1));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With