不使用length()方法的字符串长度

如何在不使用String类的length()方法的情况下找到String的length()

  • str.toCharArray().length应该有效。

  • 或者怎么样:

    str.lastIndexOf("")

    甚至可能在恒定的时间运行:)

  • 另一个

     Matcher m = Pattern.compile("$").matcher(str); m.find(); int length = m.end(); 
  • 最愚蠢的解决方案之一: str.split("").length - 1

  • 这是作弊: new StringBuilder(str).length() ? 🙂

既然没有人发布顽皮的后门方式:

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

;)

 String blah = "HellO"; int count = 0; for (char c : blah.toCharArray()) { count++; } System.out.println("blah's length: " + count); 

传递最后一个字符时,可以使用循环检查每个字符位置并捕获IndexOutOfBoundsException 。 但为什么?

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

注意:这是非常糟糕的编程习惯,效率很低。

您可以使用reflection来检查String类中的内部变量,特别是count

只是用最愚蠢的方法完成这个我可以想出:生成所有可能的长度为1的字符串,使用equals将它们与原始字符串进行比较; 如果它们相等,则字符串长度为1.如果没有字符串匹配,则生成长度为2的所有可能字符串,比较它们,对于字符串长度2.等等。继续,直到找到字符串长度或Universe结束,无论先发生什么。

尝试以下代码

  public static int Length(String str) { str = str + '\0'; int count = 0; for (int i = 0; str.charAt(i) != '\0'; i++) { count++; } return count; } 

已经发布了半最好的方法,没有比String#length更好的了…

将System.out重定向到FileOutputStream,使用System.out.print(而不是println()!)来打印字符串并获取文件大小 – 这等于字符串长度。 测量后不要忘记恢复System.out。

😉

隐藏长度()用法:

  String s = "foobar"; int i = 0; for(char c: s.toCharArray()) { i++; } 

这是另一种方式:

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

本着同样的精神(虽然效率低得多):

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

甚至:

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

这是一个完整的程序,您可以编译并运行它。

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

只是为了完整性(这根本不推荐):

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

这是因为char是UTF-16代码单元, str.length()返回此类代码单元的数量。 每个UTF-16代码单元占用2个字节,因此我们除以2.此外,没有用UTF-16BE写入的字节顺序标记。

我们可以像字符数组一样迭代字符串,并按照这种方式计算(更实际的方式):

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

使用for循环的“foreach”版本

更慢一点

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

甚至更慢,

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

很好的解决方案。 还有一些。

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

这是一个递归版本:

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

还有更多

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

我怎么能忘记在合理的时间内实际工作的一个? (字符串#length仍然是首选。)

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