Java 子串索引范围

Java 子串索引范围,java,string,substring,Java,String,Substring,代码: public class Test { public static void main(String[] args) { String str = "University"; System.out.println(str.substring(4, 7)); } } 输出:ers 我真的不明白substring方法是如何工作的。索引是否从0开始?如果我从0开始,e在索引4处,而charI在7处,那么输出将是ersi请参见。它是第一个参

代码:

public class Test {
    public static void main(String[] args) {
        String str = "University";
        System.out.println(str.substring(4, 7));
    }   
}
输出:
ers


我真的不明白substring方法是如何工作的。索引是否从0开始?如果我从0开始,
e
在索引4处,而char
I
在7处,那么输出将是
ersi
请参见。它是第一个参数的包含索引,第二个参数的独占索引。

两者都是基于0的,但开始是包含的,结束是独占的。这确保生成的字符串长度为
start-end

为了使
子字符串
操作更简单,假设字符位于索引之间

01 2 3 4 5 6 7 8 9 10“E R S”范围
引述:

子字符串从指定的位置开始
beginIndex
并扩展到 索引处的字符
endIndex-1
。因此 子字符串的长度为
endIndex beginIndex


是,索引从零(0)开始。这两个参数是startIndex和endIndex,其中根据文档:

子字符串从指定的beginIndex开始,并延伸到索引endIndex-1处的字符

有关更多信息,请参阅。

0:U

1:n

2:我

3:v

4:e

5:r

6:s

7:我

8:t

9:y

开始索引是包含的

结束索引是独占的


像你一样,我觉得这不是自然而然的。通常我还是要提醒自己

  • 返回字符串的长度为

    lastIndex-firstIndex

  • 即使没有字符,也可以使用字符串的长度作为最后一个索引,并且尝试引用它会引发异常

所以

返回4个字符的字符串“
sity”
,即使位置10处没有字符。

对于子字符串(startIndex,endIndex),startIndex是包含的,endIndex是独占的。startIndex和endIndex非常混乱。
我会理解子字符串(startIndex,length)来记住这一点

子字符串从开始,包括第一个给定数字位置处的字符,然后转到,但不包括最后一个给定数字处的字符

public String substring(int beginIndex, int endIndex)
beginIndex
-开始索引,包含在内

endIndex
-结束索引,独占

例如:

public class Test {

    public static void main(String args[]) {
        String Str = new String("Hello World");

        System.out.println(Str.substring(3, 8));
    }
 }
public class Test {

    public static void main(String args[]) {
        String Str = new String("Hello World");

        System.out.println(Str.substring(3));
    }
}
输出:“lo Wo”

从3到7指数

还有另一种
substring()
方法:

public String substring(int beginIndex)
beginIndex
-开始索引,包含在内。 返回从
beginIndex
到主字符串结尾的子字符串

例如:

public class Test {

    public static void main(String args[]) {
        String Str = new String("Hello World");

        System.out.println(Str.substring(3, 8));
    }
 }
public class Test {

    public static void main(String args[]) {
        String Str = new String("Hello World");

        System.out.println(Str.substring(3));
    }
}
输出:“lo World”

从3到最后一个索引

public class SubstringExample
{
    public static void main(String[] args) 
    {
        String str="OOPs is a programming paradigm...";

        System.out.println(" Length is: " + str.length());

        System.out.println(" Substring is: " + str.substring(10, 30));
    }
}
输出:

length is: 31

Substring is: programming paradigm

谢谢,这正是我发现的信息;beginIndex-开始索引,包含在内。endIndex-结束索引,独占。只需将其视为一个以0为底的字符数组,与所有其他数组一样,第二个参数是停止位置而不是结束位置。此外,如果将开始索引作为str.length(),它不会抛出IndexOutofBounds异常。它只会返回一个空字符串。