-1

I am trying to iterate through a string but it keeps throwing this error at 12.

fun main() {
    var testStr = "subject1EE/Physics - 101"

    for(i in 0..testStr.length){
        if (testStr[i].equals("/")) {
            testStr = testStr.dropLast(1)
            break
        } else {
            testStr = testStr.dropLast(1)
        }
    }

    println(testStr)
}

Error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12
    at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
    at java.base/java.lang.String.charAt(String.java:693)
    at com.example.jarnetor.TestKt.main(Test.kt:8)
    at com.example.jarnetor.TestKt.main(Test.kt)
TheWiseNerd
  • 21
  • 1
  • 4
  • You are sawing the branch you are sitting on. After 12 iterations, you have removed 12 characters from your string, and it is left with only 12 characters; `testStr[i]` is now beyond the end of the string. When iterating over a sequence you are deleting from, use `while` to control both the index and the length manually. Alternately, start from the tip of the branch (i.e. iterate from the end of the sequence to the front, as this does not mess up the indices you use later). – Amadan Sep 05 '21 at 11:28
  • Why are you iterating through the string? What are you trying to achieve? – Adam Millerchip Sep 05 '21 at 14:25
  • Does this answer your question? [What is a StringIndexOutOfBoundsException? How can I fix it?](https://stackoverflow.com/questions/40006317/what-is-a-stringindexoutofboundsexception-how-can-i-fix-it) – Zoe Sep 09 '21 at 12:00

1 Answers1

0

Your for loop will iterate from 0 up to the testStr length. But then inside the for loop, you are changing the testStr by dropping a character at a time. Of course, you will end up with an "index out of range" because your String is getting smaller but your for loop references its original length.

Assuming you want to get the substring before the slash, then you can simply do the following:

 fun main() {
    var testStr = "subject1EE/Physics - 101"

    println(testStr.substringBefore("/"))
}
João Dias
  • 16,277
  • 6
  • 33
  • 45