Java程序:替换文件中除特定单词外的所有字符为 '#'
String类的**split()**方法根据给定的正则表达式将当前字符串分割成多个子字符串。此方法返回的数组包含此字符串的每个子字符串,这些子字符串以与给定表达式匹配的另一个子字符串结尾,或者以字符串结尾。
String类的**replaceAll()**方法接受两个字符串,分别表示正则表达式和替换字符串,并将匹配的值替换为给定的字符串。
替换文件中除特定单词外的所有字符为 '#'(一种方法):
将文件内容读取到一个字符串中。
创建一个空的StringBuffer对象。
使用**split()**方法将获得的字符串分割成字符串数组。
遍历获得的数组。
如果其中的任何元素与所需的单词匹配,则将其添加到StringBuffer中。
将所有其余单词中的字符替换为“#”,并将它们添加到StringBuffer对象中。
最后将StringBuffer转换为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 ############################################
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP