如何用Java中的另一个单词替换字符串中出现的任何单词?


String类的replaceAll()方法接受两个字符串,一个代表查找字符串的正则表达式,另一个代表替换字符串。

并且,用给定的字符串替换所有匹配的序列。因此,要在字符串中用另一个单词替换某个特定单词-

  • 获取所需的字符串。

  • 通过传递表示要替换的单词(在单词边界“\b”内)的正则表达式和替换字符串作为参数,对所得字符串调用replaceAll方法。

  • 检索结果并打印。

示例

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("
"+input);       }       String contents = sb.toString();       System.out.println("Contents of the string: "+contents);       contents = contents.replaceAll("\bTutorials point\b", "TP");       System.out.println("Contents of the string after replacement: ");       System.out.println(contents);    } }

输出

Contents of the string:
Tutorials point 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 Tutorials point we provide high quality learning-aids for free of cost.
Tutorials point 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.

更新于:2019年10月10日

1K+浏览量

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.