字符串替换问题,出现给出的敏感词使用*代替
形如:输入:4
revolution
greatewall
democracy
science
cross the greatewall,we can reach every corner
输出:cross the *********,we can reach every corner2
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int n = in.nextInt();
in.nextLine();
String[] sTest = new String[n];
for(int i = 0;i < n;i++){
sTest[i] = in.nextLine();
}
String str = in.nextLine();
//将字符串按逗号和空格进行分割,并且统计每个字符串的个数
String[] sArr = str.split("\\s+,?|,?\\s+");
Map<String, Integer> maps = new HashMap<String, Integer>();
for(int i = 0;i < sArr.length;i++){
if(maps.isEmpty()){
maps.put(sArr[i], 1);
}else if(maps.containsKey(sArr[i])){
int val = maps.get(sArr[i]);
maps.put(sArr[i], val+1);
}else{
maps.put(sArr[i], 1);
}
}
int l = 0,first = 0,end = 0;
for(int i = 0;i< n;i++){
if(maps.containsKey(sTest[i])){
int val = maps.get(sTest[i]);//字符串的个数,进行几次替换
while(val != 0){
l = sTest[i].length();//字符串的长度
first = str.indexOf(sTest[i]);//sTest在str出现的开始位置
end = first + l -1;//结束位置
str = replace(str, first, end);
val--;
}
}
}
System.out.println(str);
}
}
//字符串替换工作,将字符串从first到end之间的字符串替换为*
public static String replace(String string,int first,int end){
StringBuffer sb = new StringBuffer();
int l = end - first + 1;
for(int i = 0;i < first;i++){
sb.append(string.charAt(i));
}
for(int i = 0;i<l;i++){
sb.append("*");
}
for(int i = end + 1;i < string.length();i++){
sb.append(string.charAt(i));
}
return sb.toString();
}
}