Search code examples
androidkotlinstringbuilder

Kotlin with(String) strange behavior


I have simple block of code wich should parse String like "5555;John Snow"

//Example of code without string population

val str = StringBuilder() 

with(str.toString().trim()) {
    card.id = substring(0, indexOf(";"))
    card.name = substring(indexOf(";" + 1, length))
}

But when it try to take name, throws an error

java.lang.StringIndexOutOfBoundsException: length=SOME_LENGHT; index=-1

Debuged and checked, String is correct. It's even work some times in debugger


Solution

  • Don't bother with indexes:

    with(str.toString().trim()) {
        card.id = substringBefore(";")
        card.name = substringAfter(";")
    }