Java中的substringAfter()和substringBefore()函數可以用于從一個字符串中獲取子字符串。這兩個函數分別用于獲取指定字符串之后和之前的子字符串。以下是它們的用法示例:
substringAfter()函數獲取指定字符串之后的子字符串:String str = "Hello World";
String subStr = str.substringAfter("Hello "); // 獲取“Hello ”之后的子字符串
System.out.println(subStr); // 輸出“World”
substringBefore()函數獲取指定字符串之前的子字符串:String str = "Hello World";
String subStr = str.substringBefore(" World"); // 獲取“ World”之前的子字符串
System.out.println(subStr); // 輸出“Hello”
需要注意的是,如果指定的字符串不存在于原始字符串中,substringAfter()和substringBefore()函數將返回空字符串。如果需要處理這種情況,可以使用substringAfterLast()和substringBeforeLast()函數來獲取最后一個匹配字符串之后和之前的子字符串。