Index position understanding, java

huangapple go评论71阅读模式
英文:

Index position understanding, java

问题

我正在努力理解这段代码中发生了什么,我了解Java只有正向索引。

我试图理解的示例。

if ((Input.length() > 2) &&
    (Input.substring(1, Input.length() -2).contains(substring))) {
    System.out.print("Middle");

上面的代码在做什么?

英文:

I am struggling to understand what is occurring in this code, I understand Java only has positive indexing.

Example of what I am attempting to understand.

            if ((Input.length() > 2) &&
                (Input.substring(1, Input.length() -2).contains(substring))) {
                System.out.print("Middle");

What is the above code doing?

答案1

得分: 1

在Java中没有负索引。

让我们看看你的示例代码。我已经格式化了代码,以便更容易看出发生了什么。

if ((input.length() > 2) &&
       (input.substring(1, input.length() - 2).contains(substring))) {
                System.out.print("Middle");
}

字段Input应该改为小写(input)。

这个if语句的意思是如果input的字符串长度大于2,并且从位置1到位置length-2的子字符串包含substring,则执行打印"Middle"的操作。

因此,如果字符串长度为5个字符(作为示例),它将大于2,并且子字符串将包含位置1和2的字符。长度为5减2等于3。因为3是子字符串的结束索引,所以我们在位置2停止子字符串。

使用示例字符串"ABCDE",长度大于2,要测试的子字符串(包含)是"BC"。字符串仍然是"ABCDE"。

带括号的substring是一个字符串方法。contains方法中的子字符串是包含一个字符串值的字段。尽管它们具有相同的名称,但它们是两个不同的概念。

英文:

There are no negative indexes in Java.

Let's take your example code. I've formatted the code to make it easier to see what's happening.

if ((Input.length() > 2) &&
       (Input.substring(1, Input.length() - 2).contains(substring))) {
                System.out.print("Middle");
}

The field Input should be lower case (input).

The if is saying if the String length of input > 2 and if the substring from position 1 to position length, where length is the length of the string, minus 2.

So if the string is 5 characters (as an example), it would be longer than 2, and the substring would be the characters in positions 1 and 2. Length of 5 minus 2 gives 3. Since 3 is the end index of the substring, we stop the substring at position 2.

Using the example String of "ABCDE", the length is greater than 2, and the substring to be tested (contains) is "BC". The String is still "ABCDE".

The substring with the parenthesis is a String method. The substring in the contains method is a field that contains a String value. They are two different concepts even though they have the same name.

huangapple
  • 本文由 发表于 2020年8月8日 22:38:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63316602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定