Thursday, July 9, 2020

Find length of String without using java inbuilt length method

There are two ways to find the length of string without using inbuilt length method:
  1. Using toCharArray
  2. Using StringIndexOutOfBoundsException

Using toCharArray:
  • Conver string to char array using toChararray method
  • Iterate over char array and incrementing length variable.
class LenghtOfStringMain{
        public static void main(String args[]){
                String str1="This is hello world";
                System.out.println("length is :"+getLengthOfStringWithCharArray(str1));
        }
        public static int getLengthOfStringWithCharArray(String str){
                int length=0;
                char[] strCharArray=str.toCharArray();
                for(char c:strCharArray){
                        length++;
                }
                return length;
        }

Output:

        length is: 19

Using StringIndexOutOfBoundsException:

  • Initialize i with 0 and iterate over String without specifying any condition. So it will be always true.
  • Once value of i will be more than length of String, it will throw StringIndexOutOfBoundsException exception.
  • We will catch the exception and return i after coming out of catch block.

class LenghtOfStringMain
{
        public static void main(String args[])
        {
                String str1="This is hello world";
                System.out.println("length is :"+getLengthOfString(str1));
        }
        public static int getLengthOfString(String str)
        {
                int i=0;
                try{
                        for(i=0;;i++){
                        str.charAt(i);
                        }
                }
                catch(Exception e)
                {

                }
                return i;
        }
}

Output:
        length is:19

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home