簡體   English   中英

如何用arraylist中的多個匹配項替換字符串?

[英]How do I replace a string with multiple matches from an arraylist?

說我有一個字符串,例如String x "This is an example string!";

我正在嘗試從數組中查找某些[This, an, string]字詞[This, an, string]如果找到匹配項,將它們全部替換為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+)]", "*");
 }

這種工作方式,但要求必須字符串包含This, an, string出現的確切順序的字符串This, an, string

您可以使用簡單的for循環:

List<String> index = // ...
String message = "This is an example string!";
for (String word : index) {
    message = message.replace(word, "*");
}

遍歷List每個單詞。 *替換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);

輸出是

* is * * string!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM