不使用length()方法的String的长度

Rah*_*hul 9 java string

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

aio*_*obe 41

  • str.toCharArray().length 应该管用.

  • 或者怎么样:

    str.lastIndexOf("")

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

  • 另一个

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

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


Joe*_*oel 22

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


Aff*_*ffe 19

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

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);
}
Run Code Online (Sandbox Code Playgroud)

;)

  • 如果我在真实世界的代码中发现你做了类似的事情,你最终会在thedailywtf.com ;-) (7认同)
  • 我完全支持这个解决这个世俗和奇怪的任务:) (5认同)

Kev*_*ock 11

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

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

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

您可以使用反射来检查在内部变量String类,具体count.


Eri*_*ler 8

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


小智 6

尝试以下代码

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

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

    return count;
    }
Run Code Online (Sandbox Code Playgroud)