javacodex.com
Java Examples
Java Examples
memu home questions

How to get the length of a String without using the string.length() method?

One way is to iterate through the each char in the string until you get a IndexOutOfBoundsException.

StringLength.java

public class StringLength {
 
   public static void main(String[] args) {
 
      String str = "The cat in the hat";
      int length = 0;
      try {
         for (int i = 0;; i++) {
            str.charAt(i);
            length++;
         }
      } catch (IndexOutOfBoundsException e) {
         /* 
          *  IndexOutOfBoundsException is caught when the index argument  
          *  is greater than the length of the string.
          */
      }
      System.out.println("str: " + str);
      System.out.println("length: " + length);
 
   }
}
 

output

$ java StringLength
str: The cat in the hat
length: 18

Questions answered by this page:

String length without using length() method Get length of a String without using the Java Built In length method. Finding the length of the String without using inbuilt Java methods




Contact: javacodex@yahoo.com