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?
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With