-
AlgorithmsLogicSearchStringsData Types
Code fun findFirstSubString(string: String, subString: String): Int? = if (subString.isEmpty()) null else string.indexOf(subString).let { if (it == -1) null else it }
Test Cases import org.junit.Assert import org.junit.Test class SimpleSubStringSearchKtTest { fun `Substring longer than string`() { Assert.assertNull(findFirstSubString("12345", "123456")) Assert.assertNull(findFirstSubString("54321", "123456")) } fun `Empty string`() { Assert.assertNull(findFirstSubString("", "123456")) } fun `Empty substring`() { Assert.assertNull(findFirstSubString("12323123", "")) } fun `Empty substring and string`() { Assert.assertNull(findFirstSubString("", "")) } 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) } }
Output:
-
Code - fun findFirstSubString(string: String, subString: String): Int? =
if (subString.isEmpty()) nullelse subString.toRegex().find(string)?.range?.first- if (subString.isEmpty()) null
- else string.indexOf(subString).let { if (it == -1) null else it }
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}
Please sign in or sign up to leave a comment.