欢迎访问宙启技术站
智能推送

JavaString函数:substring()方法

发布时间:2023-09-07 09:30:40

Java中的substring()方法是用于从字符串中截取子字符串的方法。它有两种重载形式:

1. substring(int beginIndex):截取从指定位置开始到字符串末尾的子字符串。

2. substring(int beginIndex, int endIndex):截取从指定位置开始到指定位置结束的子字符串。

在使用substring()方法时,需要注意以下几点:

1. 字符串的索引从0开始,所以beginIndex参数代表的是截取子字符串的起始位置,该位置的字符也会被包含在内。

2. endIndex参数代表的是截取子字符串的结束位置,但该位置的字符不会被包含在内。

3. 参数beginIndex和endIndex都是以左闭右开的方式进行截取。

4. 如果指定的beginIndex或endIndex越界(小于0或大于等于字符串长度),会抛出StringIndexOutOfBoundsException异常。

5. 当beginIndex等于endIndex时,substring()方法返回的是空字符串。

下面是一些substring()方法的示例:

String str = "Hello World!";
System.out.println(str.substring(6)); // 输出:World!

String str2 = "Hello World!";
System.out.println(str2.substring(0, 5)); // 输出:Hello

String str3 = "Hello World!";
System.out.println(str3.substring(6, 11)); // 输出:World

String str4 = "Hello World!";
System.out.println(str4.substring(6, 6)); // 输出:

String str5 = "Hello World!";
System.out.println(str5.substring(-1)); // 抛出异常:StringIndexOutOfBoundsException

通过使用substring()方法,我们可以方便地截取出字符串中需要的部分,进行后续的操作。它在处理字符串时非常有用,常用于字符串分割、字符筛选、截取部分字符串等场景。