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