https://kotlinlang.org logo
#getting-started
Title
# getting-started
t

therealbluepandabear

03/03/2021, 5:05 AM
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

CLOVIS

03/03/2021, 6:57 AM
Copy code
fun alternatingCase(param: String) = param
    .toCharArray()
    .mapIndexed { index, char ->
        if (index % 2 != 0)
            char.toUpperCase()
        else
            char.toLowerCase()
    }
w

Willy Ricardo

03/03/2021, 8:17 AM
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

araqnid

03/03/2021, 10:22 AM
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

psh

03/03/2021, 12:55 PM
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

nanodeath

03/03/2021, 5:26 PM
@psh rapidly approaching shorter, but longer to read/understand :)
c

CLOVIS

03/03/2021, 8:17 PM
@psh it's quite neat but the complexity sounds awful 😅
2 Views