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
- if no substring is found the function returns NULL
- 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
}
import org.junit.Assert
import org.junit.Test
class SimpleSubStringSearchKtTest {
@Test
fun `Substring longer than string`() {
Assert.assertNull(findFirstSubString("12345", "123456"))
Assert.assertNull(findFirstSubString("54321", "123456"))
}
@Test
fun `Empty string`() {
Assert.assertNull(findFirstSubString("", "123456"))
}
@Test
fun `Empty substring`() {
Assert.assertNull(findFirstSubString("12323123", ""))
}
@Test
fun `Empty substring and string`() {
Assert.assertNull(findFirstSubString("", ""))
}
@Test
fun `Correct finding`() {
Assert.assertEquals(findFirstSubString("12345", "123"), 0)
Assert.assertEquals(findFirstSubString("54321321", "321"), 2)
Assert.assertEquals(findFirstSubString("123456789ABCDE123456789", "ABCDE"), 9)
Assert.assertEquals(findFirstSubString("123456789ABCDE123456789", "A"), 9)
Assert.assertEquals(findFirstSubString("123456789ABCDE123456789", "a"), null)
Assert.assertEquals(findFirstSubString("111234", "1234"), 2)
}
}