Java substring() 方法

substring() 方法返回字符串的子字符串。

语法:

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

参数:

  • beginIndex -- 起始索引(包括), 索引从 0 开始。
  • endIndex -- 结束索引(不包括)。

返回值

子字符串。

例子

String str = "Hello World!";
//截取str子串,从下标为6(包括6)到字符串结束
System.out.println(str.substring(6));   //World!

//截取str子串,从下标为0(包括0)到下标为5(不包括5)
System.out.println(str.substring(0, 5));    //Hello

以下是相当于从头到尾截取字符串 :

String str = "Hello World!";

//Call to 'substring(0)' is redundant(多余的)
System.out.println(str.substring(0));   //Hello World!

//Call to 'substring(0, str.length())' is redundant(多余的)
System.out.println(str.substring(0, str.length())); //Hello World!
原文地址:https://www.cnblogs.com/nieaojie625/p/13337967.html