Lesson 4
Finding Substring Occurrences in Kotlin
Introduction

Hello, and welcome to our analysis lesson. In this lesson, we will tackle a common problem in the field of string manipulations. We will learn how to find all occurrences of a substring within a larger string. The techniques you will master today can be utilized in numerous situations, such as text processing and data analysis. Are you ready to get started? Let's jump right in!

Task Statement and Description

Here is this unit's task: We have two lists of strings, both of identical lengths — the first containing the "original" strings and the second containing the substrings. Our goal is to detect all occurrences of each substring within its corresponding original string and, finally, return a list that contains the starting indices of these occurrences. Remember, the index counting should start from 0.

Example

Let's consider the following lists: Original List: { "HelloWorld", "LearningKotlin", "GoForBroke", "BackToBasics" } Substring List: { "loW", "ear", "o", "Ba" }.

The following are the expected outputs: In "HelloWorld", "loW" starts at index 3.
In "LearningKotlin", "ear" starts at index 1.
In "GoForBroke", "o" appears at indices 1, 3, and 7.
In "BackToBasics", "Ba" starts at indices 0 and 6.

Thus, when findSubString(listOf("HelloWorld", "LearningKotlin", "GoForBroke", "BackToBasics"), listOf("loW", "ear", "o", "Ba")) is invoked, the function should return:

1{ 2 "The substring 'loW' was found in the original string 'HelloWorld' at position(s) 3.", 3 "The substring 'ear' was found in the original string 'LearningKotlin' at position(s) 1.", 4 "The substring 'o' was found in the original string 'GoForBroke' at position(s) 1, 3, 7.", 5 "The substring 'Ba' was found in the original string 'BackToBasics' at position(s) 0, 6." 6}

Although this task may seem fairly straightforward, it can prove challenging. However, don't worry! We will break it down step by step.

Step-by-Step Solution: Step 1, Creating the Output List

Initially, we need to create a space to store our results. Can you think of a Kotlin data type that would be ideal for this task? That's right! A MutableList would be perfect!

Kotlin
1fun findSubString(origStrs: List<String>, substrs: List<String>): List<String> { 2 val result = mutableListOf<String>()
Step 2: Pairing Strings and Locating First Occurrence

To pair original strings with their substrings, we use a simple loop. In our case, both lists share the same length, so we can use their indices to pair them correctly. To find the first occurrence of each substring in the corresponding original string, we utilize the indexOf method:

Kotlin
1 for (i in origStrs.indices) { 2 var startPos = origStrs[i].indexOf(substrs[i])

In string.indexOf(substr), we provide the substring that we intend to locate. The function starts its search from the beginning because we have not specified a starting position.

Step 3: Locating Subsequent Occurrences

The next step is to find the subsequent instances of the substring in the original.

To do this, we will use a while loop. But when should we stop looking for more occurrences? When our indexOf function returns -1, it indicates there are no more matches to be found.

Each time we locate a match, we record its starting index in the matchIndices list, adjust the startPos, and begin the search anew:

Kotlin
1 val matchIndices = mutableListOf<Int>() 2 while (startPos != -1) { 3 matchIndices.add(startPos) 4 startPos = origStrs[i].indexOf(substrs[i], startPos + substrs[i].length) 5 }
Step 4: Formatting and Storing the Results

Finally, we format the result for improved readability and add it to the result list using Kotlin's string templates:

Kotlin
1 if (matchIndices.isNotEmpty()) { 2 val formattedResult = "The substring '${substrs[i]}' was found in the original string '${origStrs[i]}' at position(s) ${matchIndices.joinToString(", ")}." 3 result.add(formattedResult) 4 } 5 } 6 return result 7}
The Complete Solution

Here is the complete function, incorporating all the steps we have discussed so far:

Kotlin
1fun findSubString(origStrs: List<String>, substrs: List<String>): List<String> { 2 val result = mutableListOf<String>() 3 4 for (i in origStrs.indices) { 5 var startPos = origStrs[i].indexOf(substrs[i]) 6 val matchIndices = mutableListOf<Int>() 7 8 while (startPos != -1) { 9 matchIndices.add(startPos) 10 startPos = origStrs[i].indexOf(substrs[i], startPos + substrs[i].length) 11 } 12 13 if (matchIndices.isNotEmpty()) { 14 val formattedResult = "The substring '${substrs[i]}' was found in the original string '${origStrs[i]}' at position(s) ${matchIndices.joinToString(", ")}." 15 result.add(formattedResult) 16 } 17 } 18 return result 19} 20 21fun main() { 22 // Call the function 23 val result = findSubString( 24 listOf("HelloWorld", "LearningKotlin", "GoForBroke", "BackToBasics"), 25 listOf("loW", "ear", "o", "Ba") 26 ) 27 for (res in result) { 28 println(res) 29 } 30}
Lesson Summary

Well done! You've mastered a central operation in string manipulations — finding all occurrences of a substring in another string. Keep in mind that this algorithm has numerous applications in real-world scenarios. Now that we have intricately dissected the problem and provided a detailed solution, I encourage you to practice more. Future exercises will help you hone your skills further. Keep on coding and exploring!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.