Is there a more concise way of doing the following...
# getting-started
t
Is there a more concise way of doing the following:
Copy code
fun main() {
    println(alternatingCase("hello kotlin"))
}

fun alternatingCase(param: String) : String {
    val array: CharArray = param.toCharArray()
    var newString = ""
    for ((index, char) in array.withIndex()) {
        newString += if (index % 2 != 0) char.toUpperCase() else char.toLowerCase()
    }
    return newString
}
c
Copy code
fun alternatingCase(param: String) = param
    .toCharArray()
    .mapIndexed { index, char ->
        if (index % 2 != 0)
            char.toUpperCase()
        else
            char.toLowerCase()
    }
w
Copy code
fun alternating3(input: String) : String {
    return input.mapIndexed { index, c -> if (index % 2 == 0) c.toLowerCase() else c.toUpperCase() }.joinToString("")
}
@CLOVIS that's gonna return charArray
a
Maybe not more concise, I’d make the string with buildString and avoid the intermediate List<Char>:
Copy code
fun alternatingCase(param: String): String {
    return buildString(param.length) {
        var upper = false
        for (chr in param) {
            append(if (upper) chr.toUpperCase() else chr.toLowerCase())
            upper = !upper
        }
    }
}
👍 2
p
Thank you for posting this - I learned something as I was coming to a solution -
Copy code
fun alternatingCase(param: String) = param.chunked(2)
    .joinToString(separator = "", transform = String::capitalize)
n
@psh rapidly approaching shorter, but longer to read/understand :)
c
@psh it's quite neat but the complexity sounds awful 😅