10

How can I find the length of a String without using the length() method of String class?

Rahul
  • 568
  • 2
  • 6
  • 16

14 Answers14

44
  • str.toCharArray().length should work.

  • Or how about:

    str.lastIndexOf("")

    Probably even runs in constant time :)

  • Another one

    Matcher m = Pattern.compile("$").matcher(str);
    m.find();
    int length = m.end();
    
  • One of the dumbest solutions: str.split("").length - 1

  • Is this cheating: new StringBuilder(str).length()? :-)

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Nice. Reminder though (not for aioobe, just for the casual reader) it creates a new array object and copies all the characters. Obviously, there is no better way than String.length(). – Kevin Brock May 26 '10 at 05:54
25
String blah = "HellO";
int count = 0;
for (char c : blah.toCharArray()) {
    count++;
}
System.out.println("blah's length: " + count);
aioobe
  • 413,195
  • 112
  • 811
  • 826
Joel
  • 16,474
  • 17
  • 72
  • 93
19

Since nobody's posted the naughty back door way yet:

public int getLength(String arg) {
  Field count = String.class.getDeclaredField("count");
  count.setAccessible(true); //may throw security exception in "real" environment
  return count.getInt(arg);
}

;)

Affe
  • 47,174
  • 11
  • 83
  • 83
  • 5
    I fully support this solution for this mundane and weirdly limited task :) – Esko May 26 '10 at 07:11
  • 7
    If I ever catch you doing something like this in real-world code, you will end up on thedailywtf.com ;-) – Jesper May 26 '10 at 07:59
13

You can use a loop to check every character position and catch the IndexOutOfBoundsException when you pass the last character. But why?

public int slowLength(String myString) {
    int i = 0;
    try {
        while (true) {
            myString.charAt(i);
            i++;
        }
    } catch (IndexOutOfBoundsException e) {
       return i;
    }
}

Note: This is very bad programming practice and very inefficient.

You can use reflection to examine the internal variables in the String class, specifically count.

Kevin Brock
  • 8,874
  • 1
  • 33
  • 37
  • Missing a `}` and has off-by-one error. and probably won't compile since the compiler doesn't know that it will always return a value. – aioobe May 26 '10 at 05:56
  • 1
    return i belongs rather into the `finally` block. – b_erb May 26 '10 at 06:03
  • @aioobe: good catch, thanks. I was probably correcting the off-by-one when you left the comment. – Kevin Brock May 26 '10 at 06:07
  • @PartlyCloudy: no this is fine just in the catch statement since this always throws the exception. The compiler will not complain about that either since the main loop in the `try` block looks like it runs forever (static analysis). – Kevin Brock May 26 '10 at 06:09
  • What about a String being `null`? Finally is always cleaner here… – b_erb May 26 '10 at 06:16
  • @Partly - throws `NullPointerException`, the same as `myString.length()` and as I would expect. Putting the return in `finally` also produces a warning (in Eclipse). – Kevin Brock May 26 '10 at 06:20
9

Just to complete this with the most stupid method I can come up with: Generate all possible strings of length 1, use equals to compare them to the original string; if they are equal, the string length is 1. If no string matches, generate all possible strings of length 2, compare them, for string length 2. Etc. Continue until you find the string length or the universe ends, whatever happens first.

Erich Kitzmueller
  • 36,381
  • 5
  • 80
  • 102
6

try below code

    public static int Length(String str) {
    str = str + '\0';
    int count = 0;

    for (int i = 0; str.charAt(i) != '\0'; i++) {
        count++;
    }

    return count;
    }
Naren Chejara
  • 61
  • 1
  • 1
  • 1
    This will only work if the original string did not contain an `'\0'` byte already. – A.H. Jul 21 '13 at 16:03
4

For the semi-best methods have been posted and there's nothing better then String#length...

Redirect System.out to a FileOutputStream, use System.out.print (not println()!) to print the string and get the file size - this is equal to the string length. Don't forget to restore System.out after the measurement.

;-)

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
  • Beware of Unicode issues! Writing "Größte" into an UTF-8-coded file creates a file size of 8 bytes - but the string is only 6 characters long. – Erich Kitzmueller Dec 09 '15 at 09:47
3

This is a complete program you can compile and run it.

import java.util.Scanner;

class Strlen{

    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;
    }

}
mtk
  • 13,221
  • 16
  • 72
  • 112
Prashant
  • 31
  • 1
3

Hidden length() usage:

    String s = "foobar";

    int i = 0;
    for(char c: s.toCharArray())
    {
        i++;
    }
b_erb
  • 20,932
  • 8
  • 55
  • 64
3

Here's another way:

int length = 0;
while (!str.equals("")) {
    str = str.substring(1);
    ++length;
}

In the same spirit (although much less efficient):

String regex = "(?s)";
int length = 0;
while (!str.matches(regex)) {
    regex += ".";
    ++length;
}

Or even:

int length = 0;
while (!str.matches("(?s).{" + length + "}")) {
    ++length;
}
Sean
  • 29,130
  • 4
  • 80
  • 105
2

We can iterate through the string like a character array, and count that way (A much more down to earth way of doing it):

String s = "foo"
char arr[]=s.toCharArray();
int len = 0;
for(char single : arr){
  len++;
}

Using the "foreach" version of the for loop

kTiwari
  • 1,488
  • 1
  • 14
  • 21
SetSlapShot
  • 1,298
  • 1
  • 21
  • 48
2

Just for completeness (and this is not at all recommended):

int length;
try
{
   length = str.getBytes("UTF-16BE").length / 2
}
catch (UnsupportedEncodingException e)
{
   throw new AssertionError("Cannot happen: UTF-16BE is always a supported encoding");
}

This works because a char is a UTF-16 code unit, and str.length() returns the number of such code units. Each UTF-16 code unit takes up 2 bytes, so we divide by 2. Additionally, there is no byte order mark written with UTF-16BE.

Simon Nickerson
  • 42,159
  • 20
  • 102
  • 127
1

Even more slower one

public int slowerLength(String myString) {
String[] str = myString.split("");
int lol=0;
for(String s:str){
    lol++;
}
return (lol-1)
}

Or even slower,

public int slowerLength(String myString) {
String[] str = myString.split("");
int lol=0;
for(String s:str){
    lol += s.toCharArray().length;
}
return lol
}
oks16
  • 1,294
  • 11
  • 16
1

Very nice solutions. Here are some more.

int length ( String s )
{
     int length = 0 ;
     // iterate through all possible code points
     for ( int i = INTEGER . MIN_VALUE ; i <= INTEGER . MAX_VALUE ; i ++ ) 
     {
           // count the number of i's in the string
          for ( int next = s . indexOf ( i , next ) + 1 ; next != -1 ; next = s . indexOf ( i , next ) + 1 )
          {
               length ++ ;
          }
     }
     return ( length ) ;
}

Here is a recursive version:

int length ( String s )
{
     int length = 0 ;
     search :
     for ( int i = Integer . MIN_VALUE ; i <= Integer . MAX_VALUE ; i ++ )
     {
          final int k = s . indexOf ( i ) ;
          if ( k != -1 )
          {
               length = length ( s . substring ( 0 , k ) ) + length ( s . substring ( k ) ) ;
               break search ;
          }
     }
     return ( length ) ;
}

And still more

int length ( String s )
{
     int length ;
     search ;
     for ( length = 0 ; true ; length ++ )
     {
          int [ ] codePoints = new int [ length ] ;
          for ( each possible value of codePoints from {MIN_VALUE,MIN_VALUE,...} to {MAX_VALUE,MAX_VALUE,...} )
          {
               if ( new String ( codePoints ) . equals ( s ) ) { break search ; }
          }
     }
}

How could I forget one that actually works in a reasonable time? (String#length is still preferred.)

int length ( String s )
{
     String t = s . replaceAll ( "." , "A" ) ;
     int length ;
     String r = "" ;
     search :
     for ( r = "" , length = 0 ; true ; r += "A" , length ++ )
          {
               if ( r . equals ( t ) )
               {
                    break search ;
               }
          }
     return ( length ) ;
}
emory
  • 10,725
  • 2
  • 30
  • 58