is there a Regex to toggle Character case in a Str

2019-07-07 16:48发布

问题:

I have a string like

var str = "AbCdEfGhIj"

that i want to toggle each character casing, that is,

convert it to var str = "aBcDeFgHiJ"

i am currently using this code below

val bytes = "HEllo WoRLd".toByteArray()
// Swap upper and lower case letters.
    for (i in bytes.indices) {
        if (bytes[i] >= 'A'.toByte() && bytes[i] <= 'Z'.toByte())
            bytes[i] = ('a'.toInt() + (bytes[i] - 'A'.toByte())).toByte()
        else if (bytes[i] >= 'a'.toByte() && bytes[i] <= 'z'.toByte())
            bytes[i] = ('A'.toInt() + (bytes[i] - 'a'.toByte())).toByte()
    }
 System.out.print(String(bytes)) // heLLO wOrlD

Wondering if there's a regex that can do this

回答1:

As the comments say, regexes are for matching, not altering.

But the code in the question can be improved; it will fail for non-ASCII characters (and is unnecessarily complex).  Here's a more elegant version, as an extension function on String:

fun String.swapCase() = map {
    when {
        it.isUpperCase() -> it.toLowerCase()
        it.isLowerCase() -> it.toUpperCase()
        else -> it
    }
}.joinToString("")

println("HEllo WoRLd".swapCase()) // heLLO wOrlD


标签: string kotlin