String类的split()方法。将当前字符串拆分为给定正则表达式的匹配项。此方法返回的数组包含此字符串的每个子字符串,该子字符串由另一个与给定表达式匹配的子字符串终止或由该字符串的结尾终止。
String类的replaceAll()方法接受两个表示正则表达式的字符串和一个替换String,并将匹配的值替换为给定的String。
要将文件中的所有字符替换为“#”,但不包括特定单词(单向)-将文件的内容读取为字符串。
创建一个空的StringBuffer对象。
使用split()方法将获得的字符串拆分为String的int数组。
遍历获得的数组。
如果其中任何元素与所需单词匹配,请将其附加到字符串缓冲区。
将所有剩余单词中的字符替换为“#”,并将其附加到StringBuffer对象。
最后将StingBuffer转换为String。
示例
假设我们有一个名为sample.txt的文件,其内容如下:Hello how are you welcome to Nhooo 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 = "Nhooo";
for(int i = 0; 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 Nhooo we provide hundreds of technical tutorials for free.
[Hello, how, are, you, welcome, to, Nhooo, we, provide, hundreds, of, technical, tutorials, for, free.]
#######################Nhooo ############################################