In this article, we will write a recursive Java function length(String s) that computes the length of the string s.
package com.topjavatutorial.app; import java.util.Scanner; public class StringDemo { public static void main(String[] args) { System.out.println("Enter a String: "); Scanner sc = new Scanner(System.in); String s = sc.nextLine(); sc.close(); System.out.println("Length of the string is: " + length(s)); } private static int length(String str) { if (str.equals("")) return 0; else return length(str.substring(1)) + 1; } }
Output :
Enter a String:
hello
Length of the string is: 5
© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post