Yuseff
Yuseff

Reputation: 319

`string index out of range 0` how to resolve it?

The toCamelCase function takes in any kind of string and converts it into camelCase or Pascal case;

fun toCamelCase(str:String): String {
     var ans: String = str[0].toString()
    for(i in 1..str.length - 1) {
        if(str[i] != '-' && str[i] != '_' ) {
            ans += str[i]
        }
    }
    return ans
}

But the code above produces the following error

String index out of range: 0

I am a novice so please help me understand.

Edit: This piece of code worked out without any error in Kotlin playground( online kotlin editor) but is not working in codewars website

Upvotes: 0

Views: 689

Answers (1)

Minh Nguyen
Minh Nguyen

Reputation: 865

I think your code may provide that kind of error if you call your function with an empty string: e.g. toCamelCase(""). This is because you try to access index 0 regardless of the input string (in str[0].toString()).

To avoid that, you should build your ans from an empty string and append characters starting from index 0, for example changing your for(i in 1..str.length - 1) to for(i in 0..str.length - 1).

An example fix can be as follows:

fun toCamelCase(str:String): String {
    var ans: String = ""
    for(i in 0..str.length - 1) {
        if(str[i] != '-' && str[i] != '_' ) {
            ans += str[i]
        }
    }
    return ans
}

Upvotes: 3

Related Questions