RECURSIVE ALGORITHM TO FIND THE LENGTH OF A STRING
If the string has a special character as its last character then we can count all the characters preceding this character to arrive at the result. If no such special character is present then we can use the recursive approach. If the string is empty then the length is zero. This becomes the base case.For the recursive case, consider the string which will have two parts: the first character and the rest of the string. If we can find the length of the second part then we can add 1 to this value and get the result.
RecursiveLengthString(X)
1 If X is empty (has no characters)
2 The length is 0
3 else
4 The length is 1 plus the length of the string that excludes the first character.
JAVA IMPLEMENTATION
The java method will contain the input string as an argument.
For the base case we will check whether the string is empty ("") or null and return length as 0.
For the recursive case, we will use the substring method in the String class.
According to the Java documentation the substring method can be explained as follows:
public String substring(int beginIndex): This method returns new String object containing the substring of the given string from specified beginIndex (inclusive).
Assuming our input string is "abcde" then substring(1) returns all the characters in sequence except the character at index 0. So substring("abcde") from position 1 will give us "bcde". We can recursively apply the substring method on this result until the length is zero.
import java.util.Scanner;
/**
* Created by Ganesh.r.hegde on 29-Jan-18.
*/
public class RecursiveStringLength {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string whose length is required : ");
String text= scan.nextLine();
//method call
int length = strLength(text);
//display result to the user
System.out.println("The length of string "+text+" is "+length);
}
/**
*
* @param textInput The string
* @return The length of the string
*/
private static int strLength(String textInput) {
if(textInput == null || textInput.isEmpty() ){
return 0;
}else{
return 1+strLength(textInput.substring(1));
}
}
}
The method strLength(String textInput) defined above does the job for us.
The method call textInput.substring(1) returns a reference to a string containing all characters in string textInput except for the character at position 0. Then we call method strLength again with this substring as its argument. The method result is one more than the value returned from the next call to strLength. Each time we reenter the method strLength, the if statement executes with textInput referencing a string containing all but the first character in the previous call. Method strLength is called a recursive method because it calls itself.