Ad
Algorithms
Logic
Search
Strings
Data Types

Write a function called findFirstSubString that accept two not null string(string and substring) and returns the index of the first occurrence of the substring in the string.

Examples

findFirstSubString("1234","12") => returns 0
findFirstSubString("012","12") => returns 1
findFirstSubString("4321","21") => returns 2
findFirstSubString("ABCDE","21") => returns null
findFirstSubString("","21") => returns null

Notes

  1. if no substring is found the function returns NULL
  2. the function returns only the index of the first occurrence of the string
fun findFirstSubString(string: String, subString: String): Int? {
    val stringArray = string.toList()
    val substringArray = subString.toList()

    if (stringArray.size < substringArray.size || stringArray.isEmpty() || substringArray.isEmpty()) {
        return null
    }

    var counter = 0
    var startIndex = 0

    var i = 0

    while (i < stringArray.size) {
        if (stringArray[i] == substringArray[counter]) {
            if(counter == 0) {
                startIndex = i
            }

            if ((counter + 1) == substringArray.size) {
                return startIndex
            }
            counter++
            i++
        }
        else {
            if (counter > 0) {
                i = startIndex + 1
            }
            else {
                i++
            }
            counter = 0
            startIndex = 0
        }

        println(i)
    }

    return null
}