Check if String contains any of the value from List in Kotlin
To check if given string contains any of the string value from a list in Kotlin, you can iterate over the string values in List and check if the string contains that string value using String.contains()
function.
Examples
Check if given recipe string contains any of the prohibited ingredients
Consider that we have a requirement where we have the recipe of a dish in a string variable. And also we have a list of ingredients that we should not use in any of the dishes that we make for this special guest.
In the following program, we take the recipe as a string value in recipe
variable, and the list of prohibited ingredients in the prohibited
list variable. Then we check if the recipe string contains any of the prohibited ingredients.
Kotlin Program
fun main() {
val str = """Take a cup of water.
|Boil it for 10 minutes.
|Add salt, turmeric, tomatoes, and rosemary.
|Boil till it reduces to half.""".trimMargin()
val prohibitedIngredients = arrayOf("peanut", "pepper")
var isRecipeOk = true
for (ingredient in prohibitedIngredients) {
if (str.contains(ingredient)) {
isRecipeOk = false
break
}
}
if (isRecipeOk) {
println("The recipe is OK for consumption.")
} else {
println("The recipe is not approved.")
}
}
Output
The recipe is OK for consumption.
Negative Scenario
In this example, we take the recipe such that it contains a prohibited ingredient.
Kotlin Program
fun main() {
val str = """Take a cup of water.
|Boil it for 10 minutes.
|Add salt, turmeric, pepper, tomatoes, and rosemary.
|Boil till it reduces to half.""".trimMargin()
val prohibitedIngredients = arrayOf("peanut", "pepper")
var isRecipeOk = true
for (ingredient in prohibitedIngredients) {
if (str.contains(ingredient)) {
isRecipeOk = false
break
}
}
if (isRecipeOk) {
println("The recipe is OK for consumption.")
} else {
println("The recipe is not approved.")
}
}
Output
The recipe is not approved.