相关疑难解决方法(0)

Ruby中的数组切片:不合逻辑行为的解释(取自Rubykoans.com)

我正在参加Ruby Koans的练习,我发现以下我发现真的无法解释的Ruby怪癖:

array = [:peanut, :butter, :and, :jelly]

array[0]     #=> :peanut    #OK!
array[0,1]   #=> [:peanut]  #OK!
array[0,2]   #=> [:peanut, :butter]  #OK!
array[0,0]   #=> []    #OK!
array[2]     #=> :and  #OK!
array[2,2]   #=> [:and, :jelly]  #OK!
array[2,20]  #=> [:and, :jelly]  #OK!
array[4]     #=> nil  #OK!
array[4,0]   #=> []   #HUH??  Why's that?
array[4,100] #=> []   #Still HUH, but consistent with previous one
array[5]     #=> nil  #consistent with array[4] #=> nil  
array[5,0]   #=> nil  #WOW.  Now I don't understand anything anymore...
Run Code Online (Sandbox Code Playgroud)

那么为什么 …

ruby arrays

228
推荐指数
9
解决办法
2万
查看次数

为什么'substring(startIndex,endIndex)'不会抛出"超出范围"

在Java中我使用的substring()方法,我不知道为什么它不会抛出"out of index"错误.

该字符串的abcde索引从0开始到4,但该substring()方法将startIndex和endIndex作为参数,基于我可以调用foo.substring(0)并获取"abcde"的事实.

那么为什么子串(5)有效呢?该指数应该超出范围.解释是什么?

/*
1234
abcde
*/
String foo = "abcde";
System.out.println(foo.substring(0));
System.out.println(foo.substring(1));
System.out.println(foo.substring(2));
System.out.println(foo.substring(3));
System.out.println(foo.substring(4));
System.out.println(foo.substring(5));
Run Code Online (Sandbox Code Playgroud)

此代码输出:

abcde
bcde
cde
de
e
     //foo.substring(5) output nothing here, isn't this out of range?
Run Code Online (Sandbox Code Playgroud)

当我用6替换5时:

foo.substring(6)
Run Code Online (Sandbox Code Playgroud)

然后我得到错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
    String index out of range: -1
Run Code Online (Sandbox Code Playgroud)

java substring

18
推荐指数
2
解决办法
7万
查看次数

String类中的Substring方法到达它不应该的索引

如果标题不清楚,我道歉.

现在,在字符串索引从0开始.例如:

Index    0   1   2   3   4
String   H   E   L   L   O
Run Code Online (Sandbox Code Playgroud)

在这种情况下,最后一个索引是4.

如果我想尝试做这样的事情:

System.out.println("hello".charAt(5));
Run Code Online (Sandbox Code Playgroud)

它应该抛出一个"超出界限的索引".

但是,如果我尝试运行以下代码:

System.out.println("hello".substring(5));
Run Code Online (Sandbox Code Playgroud)

它确实运行!我写了类似的代码,后来注意到了,无法弄明白.

最终,问题是我们不应该达到这个指数的可能性如何?它允许我们写:

stringObj.substring(stringObj.length());
Run Code Online (Sandbox Code Playgroud)

而且它看起来不太安全,因为stringObj.length()返回一个比最后一个索引多一个的整数.

它是故意制造的,这是否有目的?如果是这样,这个目的是什么,它带来了什么好处?

java string indexing substring

5
推荐指数
1
解决办法
570
查看次数

标签 统计

java ×2

substring ×2

arrays ×1

indexing ×1

ruby ×1

string ×1