在Java中避免替换文本中的特定单词,可以使用以下方法:
String text = "I have an apple.";
String replacedText = text.replace("apple", "orange");
System.out.println(replacedText);
输出结果为:"I have an orange."
String text = "I have an apple and an application.";
String replacedText = text.replaceAll("\\bapple\\w*", "orange");
System.out.println(replacedText);
输出结果为:"I have an orange and an orange."
String text = "I have an apple.";
StringBuilder builder = new StringBuilder(text);
int index = builder.indexOf("apple");
while (index != -1) {
builder.replace(index, index + "apple".length(), "orange");
index = builder.indexOf("apple", index + "apple".length());
}
String replacedText = builder.toString();
System.out.println(replacedText);
输出结果为:"I have an orange."
以上是在Java中避免替换文本中的特定单词的几种方法。根据具体的需求和场景选择合适的方法进行替换操作。
领取专属 10元无门槛券
手把手带您无忧上云