一、什麼是substring方法
Java中的substring方法用於從字元串中獲取子字元串。它的語法方式為:
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
其中,第一個參數beginIndex表示子字元串的開始位置,第二個參數endIndex表示子字元串的結束位置(注意,不包含endIndex所在的字元)。如果只提供一個參數,則返回從該位置開始到字元串末尾的子字元串。
例如:
String str = "abcdefg";
String newStr1 = str.substring(2); // newStr1的值為"cdefg"
String newStr2 = str.substring(1, 4); // newStr2的值為"bcd"
二、關於參數的取值
在使用substring方法時,需要注意參數的取值範圍。如果提供的beginIndex小於0或大於等於字元串長度,則會拋出IndexOutOfBoundsException異常;如果提供的endIndex小於beginIndex,則會返回空字元串。
例如:
String str = "abcdefg";
String newStr1 = str.substring(0, -1); // 會拋出IndexOutOfBoundsException異常
String newStr2 = str.substring(2, 1); // 返回空字元串
三、使用substring方法的場景
1. 提取字元串的一部分
當需要從一個字元串中提取特定的子字元串時,可以使用substring方法。例如,從一個文件路徑中提取文件名:
String filePath = "/root/user/demo.txt";
int index = filePath.lastIndexOf("/");
String fileName = filePath.substring(index + 1); // fileName的值為"demo.txt"
2. 拼裝字元串
當需要按照一定的格式拼裝一些字元串時,可以使用substring方法。例如,拼接一個URL:
String protocol = "https";
String host = "www.google.com";
String path = "/search";
String url = protocol + "://" + host + path;
String newUrl = url.substring(0, url.lastIndexOf("/")) + "/image"; // newUrl的值為"https://www.google.com/image"
3. 對字元串進行截斷
當字元串過長時,需要對其進行截斷顯示,可以使用substring方法。例如,顯示一行固定長度的日誌:
String log = "2021-01-01 12:00:00 [INFO] This is a log message.";
int maxLength = 30;
String displayLog;
if (log.length() > maxLength) {
displayLog = log.substring(0, maxLength - 3) + "...";
} else {
displayLog = log;
}
System.out.println(displayLog); // 輸出"2021-01-01 12:00:00 [INFO] T..."
四、總結
Java中的substring方法是一個非常常用的字元串處理方法,可以用來提取子字元串、拼裝字元串、截斷字元串等。在使用該方法時,需要注意參數的取值範圍,以避免拋出異常或獲取到不正確的結果。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/153430.html