如何用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 生日开业蛋糕祝福语简短