How to find the length of a string without using the length method in java
Codeaft.java
class Codeaft
{
    public static void main(String args[])
    {
        String s = "CODEAFT";
        int length=0;
        for(char c: s.toCharArray())
        {
            length++;    
        } 
        System.out.println("Length of a string is: "+length);  
    }
}
Codeaft.java
class Codeaft
{
    public static void main(String args[])
    {
        String s = "CODEAFT\0";
        int length=0;
        for(int i=0; s.charAt(i)!='\0';i++)
        {
            length++;    
        } 
        System.out.println("Length of a string is: "+length);  
    }
}
Codeaft.java
class Codeaft
{
    public static void main(String args[])
    {
        String s1="CODEAFT";
        int length=0;
        for(String s2:s1.split(""))
        {
            length++;
        }
        System.out.println("Length of a string is: "+length);  
    }
}
Codeaft.java
import java.text.*;
class Codeaft
{
    public static void main(String args[])
    {
        String s="CODEAFT";
        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
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft Length of a string is: 12 codeaft@codeaft:~$
Comments and Reactions