Calculate String Length

 

This is one of the simple interview question that need to calculate String length without using length() function. There are lot of ways to find the find the length like converting String to Character array and by iterating it. Lets see simple java code to calculate string length.
Calculate String length




public class StringSize {

 public static void main(String[] args) {
  
                String str = "Java Discover";
  
                int length = getStringLength(str);
  
                System.out.printf("String - %s \nLength - %d ",str,length);
 }
 
 public static int getStringLength(String str){
  
                int length = 0;
  
                char[] array = str.toCharArray();
  for (char c : array) {
   length++;
  }
  
                return length;
 }
}


OUTPUT:


String - Java Discover 
Length - 13



No comments:
Write comments