一、String.replace方法簡介
String.replace方法是Java中常用的字元串替換方法,它可以在指定字元串中,將舊字元或舊字元串替換為新字元或新字元串。
該方法有兩種可選參數:
- char oldChar:用來替換的舊字元
- String oldString:用來替換的舊字元串
和一個必選參數:
- char newChar:新字元或新字元串
例如:
String str = "hello world!"; String newStr = str.replace("world", "java"); System.out.println(newStr); // 輸出:hello java!
二、String.replace基本用法
String.replace方法可以用來替換字元串中的某些字元或子串。
下面是一個將指定字元串中的所有相同字元替換為新字元的例子:
String str = "hello world!"; String newStr = str.replace('l', 'a'); System.out.println(newStr); // 輸出:heaao worad!
如果想要替換字元串中的某個子串,可以使用如下代碼:
String str = "hello world!"; String newStr = str.replace("world", "java"); System.out.println(newStr); // 輸出:hello java!
如果要替換所有的匹配項,可以使用replaceAll方法:
String str = "hello world!"; String newStr = str.replaceAll("l", "a"); System.out.println(newStr); // 輸出:heaao worad!
三、String.replace高級用法
1. 多字元替換
String.replace方法可以同時替換多個字元或字元串,只需要把它們寫成一個參數即可。
String str = "abc"; String newStr = str.replace("a", "A").replace("b", "B").replace("c", "C"); System.out.println(newStr); // 輸出:ABC
2. 正則表達式替換
String.replace方法還支持使用正則表達式進行替換。
例如,下面的示例將字元串中的所有數字替換為「*」:
String str = "123abc456def789"; String newStr = str.replaceAll("\\d", "*"); System.out.println(newStr); // 輸出:***abc***def***
其中,「\\d」表示數字,在Java中需要使用兩個反斜杠來表示單個反斜杠。
如果只需要替換第一個匹配項,可以使用replaceFirst方法:
String str = "123abc456def789"; String newStr = str.replaceFirst("\\d", "*"); System.out.println(newStr); // 輸出:*23abc456def789
四、注意事項
使用String.replace方法時需要注意以下幾點:
- String.replace方法返回的是新字元串,原字元串不會被修改。
- 如果要替換的舊字元或舊字元串不存在,String.replace方法不會進行任何替換,返回原字元串。
- 如果新字元或新字元串為null,會拋出NullPointerException異常。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/192160.html