替换Java字符串中的子字符串
假设以下是我们的字符串。
String str = "行尸走肉!";
我们想将子字符串“ Dead”替换为“ Alive”。为此,让我们使用以下逻辑。在这里,我们使用了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 = "行尸走肉!";
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: 行尸走肉!String after replacing substring Dead with Alive = The Walking Alive!
以上是 替换Java字符串中的子字符串 的全部内容, 来源链接: utcz.com/z/357003.html