How to find the length of a string without using the length method in java
KW.java
class KW
{
    public static void main(String args[])
    {
        String s = "KODINGWINDOW";
        int length=0;
        for(char c: s.toCharArray())
        {
            length++;    
        } 
        System.out.println("Length of a string is: "+length);  
    }
}
KW.java
class KW
{
    public static void main(String args[])
    {
        String s = "KODINGWINDOW\0";
        int length=0;
        for(int i=0; s.charAt(i)!='\0';i++)
        {
            length++;    
        } 
        System.out.println("Length of a string is: "+length);  
    }
}
KW.java
class KW
{
    public static void main(String args[])
    {
        String s1="KODINGWINDOW";
        int length=0;
        for(String s2:s1.split(""))
        {
            length++;
        }
        System.out.println("Length of a string is: "+length);  
    }
}
KW.java
import java.text.*;
class KW
{
    public static void main(String args[])
    {
        String s="KODINGWINDOW";
        int length=0;
        CharacterIterator it=new StringCharacterIterator(s);
        while(it.current()!=CharacterIterator.DONE) 
        {
            it.next();
            length++;
        }
        System.out.println("Length of a string is: "+length);  
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW Length of a string is: 12 kodingwindow@kw:~$
Advertisement