Joe Joe - 3 months ago 6
Java Question

calculate the number of characters in a string recursively

I am trying to calculate the number of characters in a string by using recursive method. here is my code in java

public class MainClass {

public int length(String str) {
if (str == null) {
return 0;
} else {
return length(str.substring(1))+1; // in eclipse it says : at MainClass.length(MainClass.java:12)
}
}

public static void main(String args[]) {
MainClass m = new MainClass();
System.out.println(m.length("ali"));
}
}


This line does not work :
return length(str.substring(1))+1;

How can I correct the code?
Thanks

Answer

You forgot the case when your String argument is an empty string, include that in your check:

if (str == null || str.length()==0) {
  return 0;
} else {   
[...]

Please note that the Exception that you get contains valuable information about what's going wrong, in this case it's probably a StringIndexOutOfBoundsException because you call substring(1) on an empty String object.