如何用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 家庭恩爱祝福语简短英文