Java String substring() 字符串截取

String substring() 方法截取字符串的某一部分,返回一个新的字符串。

substring()方法定义

substring()方法通过开始索引和结束索引来确定新的字符串内容。

String substring(int beginIndex)
String substring​(int beginIndex, int endIndex)

注意:beginIndex 是包含的,endIndex是不包含的,是左闭右开的选取,可以表示为 ‘[)’。

substring(int beginIndex)

当我们需要查找从给定索引位置开始到字符串末尾的子字符串时,仅提供开始索引即可。

String substring(int beginIndex)

  • 它返回从指定索引开始到给定字符串结尾的子字符串。
  • 索引范围为0至N,其中 N 是字符串的长度。
  • 开始索引位置包含在内,即结果子字符串将包含索引位置处的字符’beginIndex’。
  • 如果beginIndex小于零或大于给定字符串 (N) 的长度,则抛出IndexOutOfBoundsException。
  • 如果我们传递索引值 N(字符串长度),则返回一个空字符串。

substring() 示例代码

public static void main(String[] args) {
    String text = "Hello world";
    String substring = text.substring(3);
    System.out.println(substring);                     //lo world
    String substring2 = text.substring(text.length());
    System.out.println(substring2);                    // ''
    String substring3 = text.substring(0);
    System.out.println(substring3);                    //Hello world
    String substring4 = text.substring(100); //java.lang.StringIndexOutOfBoundsException: String index out of range: -89
}

substring​(int beginIndex, int endIndex)

当我们需要找到从给定索引位置开始到给定结束索引位置的子字符串时,提供两个索引:开始索引和结束索引。

String substring(int beginIndex, int endIndex)

  • 它返回从指定索引开始到结束索引位置的子字符串。
  • 索引范围为0至N其中 N 是字符串的长度。
  • 开始索引位置是包含的,结束索引位置是不包含的。即结果子字符串将包含索引位置的字符,但不包含索引结束位置的字符。
  • 如果beginIndex小于零或大于给定字符串 (N) 的长度,则抛出IndexOutOfBoundsException。此外,endIndex应大于或等于beginIndex并小于给定字符串的长度 (N)。
  • 如果我们在两个参数中传递相同的索引,则返回空字符串。

substring() 示例代码

public static void main(String[] args) {
    String text = "Hello world";
    String substring = text.substring(3,8);
    System.out.println(substring);//lo wo
}

需要注意的是,空白也将是从该方法返回的子字符串的一部分,空格也是占位的

public static void main(String[] args) {
    String text = "Hello world";
    String substring = text.substring(5,8);
    System.out.println(substring);// wo
}

索引位 5到8有三个字符,实际输出貌似是两个,实际上’ wo’最前面还有一个空格。

标签: