2

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

Vadim Kotov
  • 7,103
  • 8
  • 44
  • 57
LekeOpe
  • 2,095
  • 1
  • 15
  • 29

1 Answers1

3

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
gidds
  • 9,862
  • 1
  • 12
  • 16