Issue
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)
Solution
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("/"))
}
Answered By - João Dias
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.