在Java中编写一个程序,将文件中的所有字符替换为'#”,除了特定的单词
String类的split()方法。将当前字符串拆分为给定正则表达式的匹配项。此方法返回的数组包含此字符串的每个子字符串,该子字符串由与给定表达式匹配的另一个子字符串终止或以字符串末尾终止。
replaceAll() String 类的方法接受两个表示正则表达式的字符串和一个替换字符串,并用给定的字符串替换匹配的值。
用“#”替换文件中除特定单词之外的所有字符(一种方式)-
将文件的内容读取到字符串中。
创建一个空的StringBuffer 对象。
使用 split() 方法将获取的字符串拆分为 String 数组。
遍历得到的数组。
如果其中有任何元素与所需的单词匹配,则将其追加到 String 缓冲区。
将剩余单词中的所有字符替换为“#”,并将其追加到 StringBuffer 对象中。
-
最后将 StingBuffer 转换为 String。
>
示例
假设我们有一个名为sample.txt的文件,其中包含以下内容 -
Hello how are you welcome to Tutorialspoint we provide hundreds of technical tutorials for free.
以下程序将文件内容读取为字符串,并将其中除特定单词之外的所有字符替换为“#”。
import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; public class ReplaceExcept { public static String fileToString() throws FileNotFoundException { String filePath = "D://input.txt"; Scanner sc = new Scanner(new File(filePath)); StringBuffer sb = new StringBuffer(); String input; while (sc.hasNextLine()) { input = sc.nextLine(); sb.append(input); } return sb.toString(); } public static void main(String args[]) throws FileNotFoundException { String contents = fileToString(); System.out.println("Contents of the file: \n"+contents); //Splitting the words String strArray[] = contents.split(" "); System.out.println(Arrays.toString(strArray)); StringBuffer buffer = new StringBuffer(); String word = "Tutorialspoint"; for(int i = 0; i < strArray.length; i++) { if(strArray[i].equals(word)) { buffer.append(strArray[i]+" "); } else { buffer.append(strArray[i].replaceAll(".", "#")); } } String result = buffer.toString(); System.out.println(result); } }
输出
Contents of the file: Hello how are you welcome to Tutorialspoint we provide hundreds of technical tutorials for free. [Hello, how, are, you, welcome, to, Tutorialspoint, we, provide, hundreds, of, technical, tutorials, for, free.] #######################Tutorialspoint ############################################
以上是在Java中编写一个程序,将文件中的所有字符替换为'#”,除了特定的单词的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处
