Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何用arraylist中的多个匹配项替换字符串?_Java - Fatal编程技术网

Java 如何用arraylist中的多个匹配项替换字符串?

Java 如何用arraylist中的多个匹配项替换字符串?,java,Java,假设我有一个字符串,比如stringx“这是一个示例字符串!” 我试图从数组中找到像[This,an,string]这样的所有单词,如果找到匹配项,则将它们全部替换为*inx 到目前为止,我已经尝试了类似的变化: List<String> index = new ArrayList(); index.add("This"); index.add("an"); index.add("example"); String words = index.toString().repla

假设我有一个字符串,比如
stringx“这是一个示例字符串!”

我试图从数组中找到像
[This,an,string]
这样的所有单词,如果找到匹配项,则将它们全部替换为*in
x

到目前为止,我已经尝试了类似的变化:

List<String> index = new ArrayList();
 index.add("This");
 index.add("an");
 index.add("example");
 String words = index.toString().replaceFirst("\\[", "").replaceFirst("\\]", "");       
 Boolean result = x.contains(words);
 if (result == true){
 String newMessage = x.replaceAll("[words.split(\\W+)]", "*");
 }
List index=new ArrayList();
索引。添加(“本”);
索引。添加(“an”);
添加索引(“示例”);
String words=index.toString().replaceFirst(\\[“,”).replaceFirst(\\[“,”);
布尔结果=x.contains(字);
如果(结果==真){
字符串newMessage=x.replaceAll(“[words.split(\\W+)”,“*”);
}

这类操作可以正常工作,但要求字符串必须按照与字符串的显示顺序包含
This,an,string

您可以使用一个简单的for循环:

List<String> index = // ...
String message = "This is an example string!";
for (String word : index) {
    message = message.replace(word, "*");
}
列表索引=/。。。
String message=“这是一个示例字符串!”;
for(字符串字:索引){
message=message.replace(单词“*”);
}

反复浏览
列表中的每个单词。将
x
中的结果替换为
*
,将结果分配回
x
。大概

List<String> index = Arrays.asList("This", "an", "example");
String x = "This is an example string!";
for (String str : index) {
  x = x.replace(str, "*");
}
System.out.println(x);

此方法用于替换第一个单词This,但其余单词保持不变,“*是一个示例字符串!”。谢谢分享。改变Array.asList=。。。要从YAML文件中提取?
* is * * string!