Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: how to swap character in String

Tags:

kotlin

I would like to swap a string from "abcde" to "bcdea". So I wrote my code as below in Kotlin

var prevResult = "abcde"
var tmp = prevResult[0]

for (i in 0..prevResult.length - 2) {
    prevResult[i] = prevResult[i+1]  // Error on preveResult[i]
}

prevResult[prevResult.length-1] = tmp // Error on preveResult[prevResult.lengt-1]

It errors out as stated above comment line. What did I do wrong? How could I fix this and get what I want?

like image 212
Elye Avatar asked Mar 28 '16 09:03

Elye


1 Answers

Strings in Kotlin just like in Java are immutable, so there is no string.set(index, value) (which is what string[index] = value is equivalent to).

To build a string from pieces you could use a StringBuilder, construct a CharSequence and use joinToString, operate on a plain array (char[]) or do result = result + nextCharacter (creates a new String each time -- this is the most expensive way).

Here's how you could do this with StringBuilder:

var prevResult = "abcde"
var tmp = prevResult[0]

var builder = StringBuilder()

for (i in 0..prevResult.length - 2) {
  builder.append(prevResult[i+1])
}

builder.append(tmp)  // Don't really need tmp, use prevResult[0] instead.
var result = builder.toString()

However, a much simpler way to achieve your goal ("bcdea" from "abcde") is to just "move" one character:

var result = prevResult.substring(1) + prevResult[0]

or using the Sequence methods:

var result = prevResult.drop(1) + prevResult.take(1)
like image 113
szym Avatar answered Nov 14 '22 15:11

szym