Java 不使用 length() 方法的字符串长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2910336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Length of the String without using length() method
提问by Rahul
How can I find the length of a String without using the length()
method of String class?
如何在不使用length()
String 类的方法的情况下找到 String 的长度?
采纳答案by aioobe
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()
? :-)
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()
吗:?:-)
回答by Kevin Brock
You can use a loop to check every character position and catch the IndexOutOfBoundsException
when you pass the last character. But why?
您可以使用循环来检查每个字符的位置并IndexOutOfBoundsException
在您传递最后一个字符时捕获。但为什么?
public int slowLength(String myString) {
int i = 0;
try {
while (true) {
myString.charAt(i);
i++;
}
} catch (IndexOutOfBoundsException e) {
return i;
}
}
Note: This is verybad programming practice and very inefficient.
注意:这是非常糟糕的编程习惯,而且效率很低。
You can use reflection to examine the internal variables in the String
class, specifically count
.
您可以使用反射来检查类中的内部变量String
,特别是count
.
回答by Joel
String blah = "HellO";
int count = 0;
for (char c : blah.toCharArray()) {
count++;
}
System.out.println("blah's length: " + count);
回答by b_erb
Hidden length() usage:
隐藏长度()用法:
String s = "foobar";
int i = 0;
for(char c: s.toCharArray())
{
i++;
}
回答by Affe
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);
}
;)
;)
回答by oks16
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
}
回答by Simon Nickerson
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.
这是有效的,因为 achar
是 UTF-16 代码单元,并str.length()
返回此类代码单元的数量。每个 UTF-16 代码单元占用 2 个字节,所以我们除以 2。另外,没有用 UTF-16BE 编写的字节顺序标记。
回答by Andreas Dolk
For the semi-best methods have been posted and there's nothing better then String#length...
对于已经发布的半最佳方法,没有什么比 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.
将 System.out 重定向到 FileOutputStream,使用 System.out.print(不是 println()!)打印字符串并获取文件大小 - 这等于字符串长度。不要忘记在测量后恢复 System.out。
;-)
;-)
回答by emory
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.)
我怎么能忘记一个在合理时间内真正起作用的呢?(String#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 ) ;
}
回答by Erich Kitzmueller
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.
只是为了用我能想到的最愚蠢的方法来完成这个:生成所有可能的长度为 1 的字符串,使用 equals 将它们与原始字符串进行比较;如果它们相等,则字符串长度为 1。如果没有字符串匹配,则生成长度为 2 的所有可能字符串,比较它们,对于字符串长度为 2。依此类推,直到找到字符串长度或宇宙结束,无论先发生什么。