4

I found this post which describes how to compare two arrays against one another very well. However, if I have some input string given from user like "20394875apple29038475" or "i love apples" and I want to check if any of the strings in a string array are present in the user given string regardless of upper/lower case, how can i do this in groovy?

Let's imagine the string array we are checking to have fruits like ("apple","banana","cherry").

In this case we would return true because the substring "apple" is present in the user given string "20394875apple29038475"

... I am thinking that the best way would be something like this?:

boolean fruitFound = false

for (item in fruitArray){
    if(usrResponse.contains(item)){
        responseFound = true
    }
2

2 Answers 2

14
fruitFound = fruitArray.any{usrResponse.contains(it)}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Admiral_x Would this also ignoreCase ? So if the user types in "ApPLe" would it still find the match with fruitArray element of "I love a good apple" ?
you're welcome, no, it's case sensitive, you can do something like : fruitArray.any{usrResponse.toLowerCase().contains(it.toLowerCase())} to convert all the strings to lower case
this can also identify wheter if a ArrayList contains any keywords. I.e. check whether if 'a' or 'e' included in ['a', 'b', 'c'] : ['a', 'b', 'c'].any { ['a', 'e'].contains(it} }
1

Check this:

def fruits = ["apple","banana","cherry"]
def str = '20394875banana29038475'
assert fruits.findAll{str.contains(it)}.any{true}

EDIT: To ignore case

assert fruits.findAll{str.toLowerCase().contains(it.toLowerCase())}.any{true}

or

assert fruits*.toLowerCase().findAll{str.toLowerCase().contains(it)}.any{true}

1 Comment

Thanks @Rao . Would this also ignoreCase ? So if the user types in "ApPLe" would it still find the match with fruitArray element of "I love a good apple" ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.