替換 Java 字串中的子字串
假設我們有以下字串。
String str = "The Walking Dead!";
我們想將子字串“死亡”替換為“活著”。為此,讓我們使用以下邏輯。在此,我們使用了一個 while 迴圈,並且找到了要替換的子字串的索引。透過這種方式,我們可以逐個替換整個子字串。
int beginning = 0, index = 0;
StringBuffer strBuffer = new StringBuffer();
while ((index = str.indexOf(subStr1, beginning)) >= 0) {
strBuffer.append(str.substring(beginning, index));
strBuffer.append(subStr2);
beginning = index + subStr1.length();
}以下替換子字串的完整示例。
示例
public class Demo {
public static void main(String[] args) {
String str = "The Walking Dead!";
System.out.println("String: "+str);
String subStr1 = "Dead";
String subStr2 = "Alive";
int beginning = 0, index = 0;
StringBuffer strBuffer = new StringBuffer();
while ((index = str.indexOf(subStr1, beginning)) >= 0) {
strBuffer.append(str.substring(beginning, index));
strBuffer.append(subStr2);
beginning = index + subStr1.length();
}
strBuffer.append(str.substring(beginning));
System.out.println("String after replacing substring "+subStr1+" with "+ subStr2 +" = "+strBuffer.toString());
}
}輸出
String: The Walking Dead! String after replacing substring Dead with Alive = The Walking Alive!
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP