Kotlin String - startsWith() Function



The Kotlin string startsWith() function is used to determine whether a string or character sequence starts with a specified prefix or character. It can also check if a substring starting at a given index matches the provided prefix. The function supports case-sensitive and case-insensitive comparisons, so it can be used to validate text or analyze text.

Syntax

Following is the syntax of the Kotlin string startsWith() function −

fun String.startsWith(prefix: String, ignoreCase: Boolean = false): Boolean
fun String.startsWith(prefix: Char, ignoreCase: Boolean = false): Boolean
fun CharSequence.startsWith(prefix: CharSequence, startIndex: Int = 0, ignoreCase: Boolean = false): Boolean

Parameters

This function accepts following parameters −

  • prefix: The string or character to check for at the start of the string.
  • startIndex (optional): The index from which to start the check (only available in the CharSequence version).
  • ignoreCase (optional): If true, the case is ignored during the comparison. Default is false.

Return value

This function returns boolean value, true if the string starts with the specified prefix; otherwise, false.

Example 1

Following is the basic example, here we use the startsWith() function to check string with specified prefix in kotlin −

fun main() {
   val text = "Hello, Kotlin!"
   println(text.startsWith("Hello"))
   println(text.startsWith("hello"))
}

Output

Following is the output −

true
false

Example 2: Use startWith() ignoreCase Parameter

Now, let's look at another example of the startsWith() function. Here we are enabling the ignoreCase to true −

fun main() {
    val text = "Hello, Kotlin!"
    println(text.startsWith("hello", ignoreCase = true))
}

Output

Following is the output −

true

Example 3: Use startWith() startIndex Parameter

In this example, we use the startsWith function to validate a string using the startIndex parameter −

fun main() {
   val text = "Hello, Kotlin!"
   println(text.startsWith("Kotlin", startIndex = 7))
   println(text.startsWith("Kotlin", startIndex = 6))
}

Output

Following is the output −

true
false

Example 4

Now, let's check whether a string starts with a particular prefix.

fun main() {
   val text = "Hello, tutorialspoint!"
   println(text.startsWith('H'))
   println(text.startsWith('h'))
}

Output

Following is the output −

true
false
kotlin_strings.htm
Advertisements