substring()
方法从字符串中提取一个子字符串并返回它。
示例
class Main { public static void main(String[] args) { String str1 = "java is fun"; // extract substring from index 0 to 3 System.out.println(str1.substring(0, 4)); } } // Output: java
substring() 的语法
substring()
方法的语法是:
string.substring(int startIndex, int endIndex)
这里,
string 是
String
类的对象。
substring() 参数
substring()
方法有两个参数。
substring() 返回值
substring()
方法从给定的字符串返回一个子字符串。
endIndex-1
处的字符。
如果未传递 endIndex,则子字符串从指定索引处的字符开始,并延伸到字符串的末尾。
注意: 你会得到一个错误,如果,
示例 1: 没有结束索引的 Java substring()
class Main { public static void main(String[] args) { String str1 = "program"; // from the first character to the end System.out.println(str1.substring(0)); // program // from the 4th character to the end System.out.println(str1.substring(3)); // gram } }
示例 2: 带有结束索引的 Java substring()
class Main { public static void main(String[] args) { String str1 = "program"; // from 1st to the 7th character System.out.println(str1.substring(0, 7)); // program // from 1st to the 5th character System.out.println(str1.substring(0, 5)); // progr // from 4th to the 5th character System.out.println(str1.substring(3, 5)); // gr } }
如果您需要从给定字符串中找到指定子字符串第一次出现的索引,请使用 Java String indexOf().