2017-05-24 59 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