java中替换所有指定的字符_程序用“#”替换文件中的所有字符,但Java中的特定单词除外...

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 ############################################

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值