用 Java 编写的程序,用"#"替换文件中除特定单词之外的所有字符
javaobject oriented programmingprogramming更新于 2024/2/17 23:08:17
String 类的 split() 方法。根据给定的正则表达式拆分当前字符串。此方法返回的数组包含此字符串的每个子字符串,这些子字符串以与给定表达式匹配的另一个子字符串结尾或以字符串结尾结尾。
String 类的 replaceAll() 方法接受两个字符串(分别表示正则表达式和替换字符串),并用给定的字符串替换匹配的值。
要用"#"替换文件中的所有字符除了特定的单词(单向)−
将文件内容读取为字符串。
创建一个空的 StringBuffer 对象。
使用 split() 方法将获得的字符串拆分为字符串数组。
遍历获得的数组。
如果其中有任何元素与所需单词匹配,则将其附加到字符串缓冲区。
用‘#’ 替换所有剩余单词中的字符并将它们附加到 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 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

