5

I am trying to change the character in a string to some other character.

Here is my code

fun main(args: Array<String>) {
    var str: String = "H...H"
    
    for(i in 0..str.length-1) {
        
        if( str[i] == '.') 
            str[i] = 'B'
    }
    println(ans)
    
}

But this produces the error:

jdoodle.kt:20:16: error: no set method providing array access
            str[i] = 'B'

But the following code works fine:

fun main(args: Array<String>) {
    var str: String = "H...H"
    var ans : String = ""
    for(i in 0..str.length-1) {
        if( str[i] == 'H') 
            ans += str[i]
        else if( str[i] == '.') 
            ans += 'B'
    }
    println(ans)
    
}

I just want to change all the ..... in the string to B.

Like "H...H" to "HBBBH"

Why is the first code not working?

1 Answer 1

8

The first example does not work because Strings in kotlin are immutable and you cannot change characters. Instead, you have to create a new String, like your second example (which, in fact, creates a new String for each time through the loop).

Kotlin has a replace function for you:

fun main() {
    val input = "H...H"
    val output = input.replace('.', 'B')
    println(output)  // Prints "HBBBH"
}
Sign up to request clarification or add additional context in comments.

2 Comments

But when we create that new string that too must be immutable then why on each iteration we are able to add a new character to the string. Because as far as I know immutables are read only.
When you do "ans += 'B'", you are telling Kotlin "Create me a new string of ans + B". So you are creating a NEW string every time you append a character. Go change ans to a val instead of a var, it won't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.