简体   繁体   中英

Java - Matching a string against an array of strings

I have an array of strings, for example String[] arr = ["question", "This", "is", "a"];

and I have a single string, for example String q = "a foo This bar is This foo question a bar question foo"; (contrived example, I know).

What would be the best way for me to match arr against q and print out all occurrences of arr[i] , but not in order? Because every time I try to do this, it gives me back the original array, in the order they originally appeared in arr , instead of all occurrences in the order they appeared.

In simpler terms, I want my result to be something like ["a", "This", "is", "This", "question", "a", "question"] and instead I'm just getting the original array.

My code:

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]);
        }
    }
}

I realize this is probably a pretty glaring error, so thanks in advance for your patience.

Don't loop over the array, loop over the String, like

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);
    }
}

You could have avoided the List , and loop over the array, but I find the code much clearer this way.

You can split the string into an array of each word and then loop through each word in the string array.

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);
    }
  }
}

How about (1) count the occurrences (2) print the result?

    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));
        }
    }

Prints

2   question
2   This
1   is
2   a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM