This article explores different ways to check if a string starts or ends with any of the given substrings in Kotlin.

1. Using startsWith() / endsWith() function

A simple solution is to use the startsWith() function to check if a string matches against any of the given substrings with an OR operator. The startsWith() function returns a boolean value depending upon the string starts with the specified substring or not.

Download Code

 
To check if the string ends with the specified substring or not, use the endsWith() function.

Download Code

2. Using any() function

A better solution is to construct a list from the given substrings and call the any() function on the list. It returns true if at least one element matches the supplied predicate. To check for “starts with”, use the startsWith() function as predicate.

Download Code

 
The following solution replaces the explicit parameter s with it:

Download Code

 
To check if the string ends with the specified substring or not, use the endsWith() function.

Download Code

 
This can also be achieved using a loop. Here’s the equivalent version of the above code:

Download Code

That’s all about checking if a string starts or ends with any of the given substrings in Kotlin.