Finding the length of the String in multiple ways

package com.examples.string;


public class FindLength {

public static void main(String[] args) {
// TODO Auto-generated method stub

String str=" hello world";

int n1=str.toCharArray().length;

System.out.println(n1);


int n2= str.lastIndexOf("");

System.out.println(n2);



int n3=str.split("").length - 1;

System.out.println(n3);


}

}


package com.examples.string;

import java.util.Scanner;

public class LengthTest2 {
public static void main(String...args){
        Scanner sc = new Scanner(System.in);
        
        System.out.print("\nEnter Your Name =>" +"  ");
        
        String ab = sc.nextLine();
        
        System.out.println("\nName Length is:" +len(ab));
    }

    public static int len(String ab){
   
        char[] ac = ab.toCharArray();
        
        int i = 0, k = 0;
        

        try{
       
            for(i=0,k=0;ac[i]!='\0';i++)
           
                k++;
        }
        catch(Exception e){
        }
        return k;
    }

}

Search This Blog

All the rights are reserved to this blog is belongs to me only.. Powered by Blogger.