方法substring()返回一个新字符串,该字符串是给定字符串的子字符串。 Java String substring()方法用于根据传递的索引获取给定字符串的子字符串。 此方法有两种形式。
1、String substring(int beginIndex)
返回从指定索引即beginIndex开始到字符串末的子字符串。 例如“Chaitanya” .substring(2)将返回“ aitanya”。 beginIndex包含在内。 如果beginIndex小于零或大于String的长度,则会引发IndexOutOfBoundsException。
2、String substring(int beginIndex, int endIndex)
返回从指定的beginIndex开始到endIndex-1处的子字符串。因此,子字符串的长度为endIndex-beginIndex。 也就是说,在获取子字符串时,包含beginIndex而不包含endIndex。
例如“Chaitanya” .substring(2,5)将返回“ ait”。 如果beginIndex小于零或beginIndex> endIndex或endIndex大于String的长度,则抛出IndexOutOfBoundsException。
代码示例:
public class SubStringExample{
public static void main(String args[]) {
String str= new String("quick brown fox jumps over the lazy dog");
System.out.println("Substring starting from index 15:");
System.out.println(str.substring(15));
System.out.println("Substring starting from index 15 and ending at 20:");
System.out.println(str.substring(15, 20));
}}
输出:
Substring starting from index 15:
jumps over the lazy dog
Substring starting from index 15 and ending at 20:
jump
网友评论