2017-05-24 93 views
0

我有一個字符串數組的數組,例如 String[] arr = ["question", "This", "is", "a"];爪哇 - 匹配的字符串的字符串對

和我有一個單一的字符串,例如String q = "a foo This bar is This foo question a bar question foo";(人爲的例子,我知道)。

什麼是最好的辦法,我爲了配合arrq並打印出的arr[i]所有出現,但?因爲每次我嘗試這樣做時,它都會將原始數組的順序返回給我,它們最初出現在arr中,而不是它們出現順序中的所有事件。

簡而言之,我希望我的結果是類似["a", "This", "is", "This", "question", "a", "question"]的東西,而我只是獲取原始數組。

我的代碼:

public static void ParseString(String[] arr, String q) { 
    for (int i = 0; i < arr.length; i++) { 
     if (q.contains(arr[i])) { 
      System.out.println(arr[i]); 
     } 
    } 
} 

我意識到這可能是一個很明顯的錯誤,所以在此先感謝您的耐心。

+0

只需使用正則表達式。正則表達式默認情況下,從左到右檢查字符串。然後找到的所有匹配按目標字符串中的出現順序排列。因此,使用array =>'(question | This | is | a)'來創建一個正則表達式。如果你有一個靜態的巨大數組,使用[這個工具](http://www.regexformat.com)來創建一個正則表達式三元樹字符串。將它複製到源代碼中,然後在運行時用它構造一個正則表達式對象。例如[75,000字詞典正則表達式](http://www.regexformat.com/Dnl/_Samples/_Ternary_Tool%20(Dictionary)/___txt/_ASCII_175,000_word_Mix_A-Z_Multi_Lined.txt) – sln

回答

0

不要循環陣列上,循環遍歷字符串,如

String q = "a foo This bar is This foo question a bar question foo"; 
String[] arr = {"question", "This", "is", "a"}; 
List<String> list = Arrays.asList(arr); 
for(String s:q.split(" ")){ 
    if(list.contains(s)){ 
     System.out.println(s); 
    } 
} 

你可能已經避免了List和循環陣列上,但我發現的代碼更清楚這種方式。

0

您可以將字符串拆分爲每個單詞的數組,然後遍歷字符串數組中的每個單詞。

String[] arr = {"question", "This", "is", "a"}; 
String q = "a foo This bar is This foo question a bar question foo"; 
String[] splitString = q.split(" "); 

for (String wordString: splitString) { 
    for (String wordArray : arr) { 
    if (wordString.equalsIgnoreCase(wordArray)) { 
     System.out.println(wordArray); 
    } 
    } 
} 
0

如何(1)計算出現次數(2)打印結果?

public void countWords() { 
     String[] queries = { "question", "This", "is", "a" }; 
     String data = "a foo This bar is This foo question a bar question foo"; 

     //prepare index 
     Map<String, Integer> index= new HashMap<>(); 
     for (String w : data.split(" ")) { 
      Integer count=index.get(w); 
      if(count==null){ 
       index.put(w, 1); 
      }else{ 
       index.put(w, count+=1); 
      } 
     } 
     //query index 
     for(String w:queries){ 
      int i=index.get(w); 
      System.out.println(String.format("%d\t%s", i,w)); 
     } 
    } 

打印

2 question 
2 This 
1 is 
2 a