Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to detect if a string contains multiple words

Tags:

I am trying to create a program that detects if multiple words are in a string as fast as possible, and if so, executes a behavior. Preferably, I would like it to detect the order of these words too but only if this can be done fast. So far, this is what I have done:

if (input.contains("adsf") && input.contains("qwer")) {     execute();           } 

As you can see, doing this for multiple words would become tiresome. Is this the only way or is there a better way of detecting multiple substrings? And is there any way of detecting order?

like image 333
Silver Avatar asked Sep 19 '13 01:09

Silver


People also ask

How do you know if a variable contains multiple values?

To check if a variable is equal to one of multiple values:Add the values to an array. Call the includes() method on the array. The includes method will return true if the value is contained in the array.

How do I check if a string contains text?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How do you check if a string contains some characters?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.


2 Answers

I'd create a regular expression from the words:

Pattern pattern = Pattern.compile("(?=.*adsf)(?=.*qwer)"); if (pattern.matcher(input).find()) {     execute(); } 

For more details, see this answer: https://stackoverflow.com/a/470602/660143

like image 157
Christoph Walesch Avatar answered Sep 27 '22 22:09

Christoph Walesch


Editors note: Despite being heavily upvoted and accepted, this does not function the same as the code in the question. execute is called on the first match, like a logical OR.

You could use an array:

String[] matches = new String[] {"adsf", "qwer"};  bool found = false; for (String s : matches) {   if (input.contains(s))   {     execute();     break;   } } 

This is efficient as the one posted by you but more maintainable. Looking for a more efficient solution sounds like a micro optimization that should be ignored until proven to be effectively a bottleneck of your code, in any case with a huge string set the solution could be a trie.

like image 20
Jack Avatar answered Sep 27 '22 21:09

Jack