如何用Java中的另一个单词替换字符串中所有出现的单词?
String类的replaceAll()方法接受两个字符串,一个代表正则表达式以查找字符串,另一个代表替换字符串。
并且,用给定的String替换所有匹配的序列。因此,用String中的另一个单词替换特定单词-
获取所需的字符串。
通过传递对表示要替换的单词的正则表达式(在单词边界“\b”内)和替换字符串作为参数,对获得的字符串调用全部替换方法。
检索结果并打印。
示例
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ReplacingWords {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("D://sample.txt"));
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append("\n"+input);
}
String contents = sb.toString();
System.out.println("Contents of the string: "+contents);
contents = contents.replaceAll("\\bnhooo.com\\b", "TP");
System.out.println("Contents of the string after replacement: ");
System.out.println(contents);
}
}输出结果
Contents of the string: nhooo.com originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. At nhooo.com we provide high quality learning-aids for free of cost. nhooo.com recently developed an app to help students from 6th to 12th. Contents of the string after replacement: TP originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. At TP we provide high quality learning-aids for free of cost. TP recently developed an app to help students from 6th to 12th.
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语