Yuseff
Yuseff

Reputation: 319

How to change the characters in a string in kotlin

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?

Upvotes: 5

Views: 6207

Answers (1)

Todd
Todd

Reputation: 31710

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"
}

Upvotes: 8

Related Questions