Kotlin String Methods

The Kotlin String class has an indexOf() method that allows developers to the position of a character or set of characters within a string. Such an operation is especially useful in situations where you may need to break a string into a substring or divide a string into different parts. Let’s go over the indexOf() method with a few examples.

indexOf

indexOf(Char)

The indexOf(Char) method is used to search for a single character within a string. It will return the index where the character was first found or -1 if the string doesn’t contain such a character.

val paragraph = 
    "I am Sam.\n" +
    "Sam I am.\n" +

    "That Sam-I-am!\n" +
    "That Sam-I-am!\n" +
    "I do not like\n" +
    "That Sam-I-am!\n" +

    "Do you like\n" +
    "Green eggs and ham?\n" +

    "I do not like them,\n" +
    "Sam-I-Am\n" +
    "I do not like\n" +
    "Green eggs and ham.\n"

//Index of letter a => 2
println("Index of letter a => " + paragraph.indexOf('a'))

The letter ‘a’ is the 3rd character in the example string. Since computers count starting at 0, the result is 2. This method also has an optional argument that allows it to ignore case.

indexOf(String)

If we want to find where a certain substring begins, we use the indexOf(String) method. It works just like its Char counterpart.

//Index of 'Green eggs and ham' => 91
println("Index of 'Green eggs and ham' => " + paragraph.indexOf("Green eggs and ham"))

The substring “Green eggs and ham” is found at position 91. Once again, this method returns -1 if the search string isn’t found. We can also use the ignoreCase optional argument when we do not care about case sensitivity.

indexOf(Char, Int), indexOf(String, Int)

The indexOf method has an optional startIndex parameter that takes an int value. By default, startIndex is 0, which is why indexOf starts at the beginning of the string. If we want to start looking in the middle of the string, we need to pass a value to startIndex. Let’s look at an example of where we can find all occurrences of the letter ‘I’.

var fromIndex = 0
while(paragraph.indexOf('I', fromIndex) > -1){
    fromIndex = paragraph.indexOf("I", fromIndex)
    println("Found at => " + fromIndex)
    fromIndex++
}

Output

Found at => 0
Found at => 14
Found at => 29
Found at => 44
Found at => 50
Found at => 73
Found at => 111
Found at => 135
Found at => 140

The code tracks each index with a fromIndex variable. We enter into a while loop that continues until indexOf returns -1. With each iteration of the loop, we update fromIndex using indexOf() and pass in the old value of fromIndex. That causes the search to keep moving forward. After we print the index, we need to increment fromIndex by 1 because indexOf is inclusive. Should we fail to increment fromIndex, we will enter into an infinite loop because indexOf will continue to return the same value.

lastIndexOf

Strings also have a lastIndexOf() method that is a cousin to the indexOf() method. It takes the same arguments as indexOf(), but rather than returning the first occurence of the search character or string, it returns the last occurence instead.

//Last index of 'eggs' => 160
println("Last index of 'eggs' => " + paragraph.lastIndexOf("eggs"))

startsWith(), endsWith()

The startsWith() and endsWith() methods are convience methods that are used to check if a string starts or ends with a supplied prefixString. It also has an optional offset parameter that allows for searching in the middle of the string.

//paragraph starts with 'I am Sam' => true
println("paragraph starts with 'I am Sam' => " + paragraph.startsWith("I am Sam"))
//paragraph ends with 'Green eggs and ham. => true
println("paragraph ends with 'Green eggs and ham. => " + paragraph.endsWith("Green eggs and ham.\n"))

Putting it Together

Here is an example program followed by the output.

fun main(args : Array<String>){
    val paragraph =
        "I am Sam.\n" +
        "Sam I am.\n" +

        "That Sam-I-am!\n" +
        "That Sam-I-am!\n" +
        "I do not like\n" +
        "That Sam-I-am!\n" +

        "Do you like\n" +
        "Green eggs and ham?\n" +

        "I do not like them,\n" +
        "Sam-I-Am\n" +
        "I do not like\n" +
        "Green eggs and ham.\n"


    println("Index of letter a => " + paragraph.indexOf('a'))
    println("Index of 'Green eggs and ham' => " + paragraph.indexOf("Green eggs and ham"))
    println("Finding all occurrences of 'I'...")
    var fromIndex = 0
    while(paragraph.indexOf('I', fromIndex) > -1){
        fromIndex = paragraph.indexOf("I", fromIndex)
        println("Found at => " + fromIndex)
        fromIndex++
    }
    println("Last index of 'eggs' => " + paragraph.lastIndexOf("eggs"))
    println("paragraph starts with 'I am Sam' => " + paragraph.startsWith("I am Sam"))
    println("paragraph ends with 'Green eggs and ham. => " + paragraph.endsWith("Green eggs and ham.\n"))
}

Output

Index of letter a => 2
Index of 'Green eggs and ham' => 91
Finding all occurrences of 'I'...
Found at => 0
Found at => 14
Found at => 29
Found at => 44
Found at => 50
Found at => 73
Found at => 111
Found at => 135
Found at => 140
Last index of 'eggs' => 160
paragraph starts with 'I am Sam' => true
paragraph ends with 'Green eggs and ham. => true
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: