如何在 Java 中使用 java.lang.String 类的 substring() 方法?

javaobject oriented programmingprogramming更新于 2024/5/11 22:47:00

substring() 方法返回一个 String 数据类型,该数据类型对应于从起始索引开始到结束索引的原始 String。如果未指定结束索引,则必须确保 endIndex  是字符串长度。由于我们处理的是字符串,索引从 '0' 位置 开始。

语法

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

beginIndex:我们想要开始剪切或子串化字符串的起始索引或位置。

endIndex:  我们想要结束剪切或子串化字符串的结束索引或位置。

此方法 返回一个字符串数据类型 ,它对应于我们剪切的字符串部分。如果未指定 endIndex ,则结束索引被假定为字符串长度 -1,并且如果 beginIndex 为负数大于字符串的长度,则会抛出 IndexOutOfBoundsException 

示例

public class StringSubstringTest{
   public static void main(String[] args) {
      String str = "Welcome to Tutorials Point";
      System.out.println(str.substring(5));
      System.out.println(str.substring(2, 5));
      str.substring(6);
      System.out.println("str value: "+ str);
      String str1 = str.substring(5);
      System.out.println("str1 value: "+ str1);
   }
}

输出

me to Tutorials Point
lco
str value: Welcome to Tutorials Point
str1 value: me to Tutorials Point

相关文章