Effectively check if a string contains a string of words

Say I have several sets of words, such as: (water, flour, eggs) and (beans, water, milk)

If the user enters a string containing all these words in any order, a message is displayed. For example, "I have eggs, water and flour" β†’ "It makes a cake."

What is the most efficient way to do this, assuming that there can be a large number of word sets and message combinations to check for each line that the user enters.

My initial idea is to use .contains:

for(each-word-set) { i = word-set.length; for(each-word) { if(string.contains(word)) { j++ } } if(i == j) { //Yes this string contains all words. } } 

Is there a better way than this?

+6
source share
3 answers

My initial way: Using space as a delimiter.

We can do the following.

Actions

Create a list. Properly

1) Use the Java split function. Creation of an array.

  List<String> list = new ArrayList<String>(Arrays.asList(string.split(" ")))`; 

2) Create a hash map.

 Map<String, String> hash = new HashMap<String, String>(); for(i = 0 ; i < list.length(); i++) { hash.put(list[i], list[i]); } 

Where list[i] is your key.

3) Get matches.

Now when the user enters the word you are interested in, you can use containsKey
command. for instance

  if (hash.containsKey("flour") && hash.containsKey("water") && hash.containsKey("beans"); println("Whatever you want"); 

It should be noted that creating a HashTable is useful for large datasets. Here is the link you must see in order to see the benefits. Retrieving data from a hash table is O (1), therefore, almost instantly.

Hope this was helpful.

+2
source

Cancel my comment. A few more errors have occurred. My final decision would be:

 public class Someclass { public static void main(String[] args) { String[] words = { "water", "flour", "eggs", "beans", "water", "milk" }; String[] testStrings = { "water flour eggs beans water milk", "somewhat else", "wader flour ekks beans water milk" }; for (String string : testStrings) { boolean found = true; for (String word : words) { if (!string.contains(word)) { found = false; break; } } if (found) { System.out.println(string + " - That makes a cake"); } else { System.out.println(string + " - That makes no cake"); } } } } 
0
source
 You can first create an array or list of strings splitted by space as: List<string>userStr= userEntry.split(" "); Now use extended for loop within another loop as: for(String s: userStr) { for(String d: yourList){ if(s.equals d){ //your code break; } } } 
0
source

Source: https://habr.com/ru/post/971782/


All Articles