gpt4 book ai didi

java - 替代 replace() 或 replaceAll() 方法

转载 作者:行者123 更新时间:2023-11-30 09:12:14 26 4
gpt4 key购买 nike

我们有一个要求,我们必须替换一个字符串。但是我们不应该使用 replace() 或 replaceAll() 方法。我们如何在 Java 中实现这一目标?

例如:

一弦:生活是踏实的(这里的 Life 字符串必须替换为 'Everything in the world')

预期输出:世间万物皆实用

最佳答案

检查这个。

public class ReplaceTest {

public static void main(String[] args) {
String str = "Life is practical"; //At first
testReplace(str);

str = "I have Life"; //At last
testReplace(str);

str = "I have Life, Life is beautiful"; //in the mid
testReplace(str);


}

private static void testReplace(String str) {
String[] strArr = str.split("Life");
StringBuilder newStr = new StringBuilder(strArr[0]);
for (int i = 1; i < strArr.length; i++) {
newStr.append("Everything").append(strArr[i]);
}

if (str.endsWith("Life")) {
newStr.append("Everything");
}
System.out.println(newStr.toString());

}

}

输出:
一切都很实用
我拥有一切
我拥有一切,一切都很美好

关于java - 替代 replace() 或 replaceAll() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21693212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com