What's the most efficient way to reverse the case of a string?
input = "Hello World"
output = "hELLO wORLD"
Here upper case character will be converted to lower case and vice versa.
Is there any default library support to do this?
What's the most efficient way to reverse the case of a string?
input = "Hello World"
output = "hELLO wORLD"
Here upper case character will be converted to lower case and vice versa.
Is there any default library support to do this?
In Kotlin I would propose something like this:
fun String.reverseCase(): String = map { if (it.isUpperCase()) it.toLowerCase() else it.toUpperCase() }.joinToString("")
Convert every Char in the String to its opposite and then join to String with no delimiter.
Which can be used as follows:
val input = "Hello WorLD"
val expected = "hELLO wORld"
input.reverseCase() shouldBeEqualTo expected
String extension function to reverse the case of a string:
Way 1: Using CharArray
fun String.reverseCaseOfString(): String {
val inputCharArr = toCharArray() // Converting the input to char array
var output = ""
for (i in 0 until inputCharArr.size) {
output += if (inputCharArr[i].isUpperCase()) { // Checking the character is in uppercase or not
inputCharArr[i].toLowerCase() // Converting the char to lower case
} else {
inputCharArr[i].toUpperCase() // Converting the char to upper case
}
}
return output
}
Way 2: Using CharIterator
private fun String.reverseCaseOfString(): String {
val charIterator = iterator() // CharIterator of string
var output = ""
for (char in charIterator) {
output += if (char.isUpperCase()) { // Checking the character is in uppercase or not
char.toLowerCase() // Converting the char to lower case
} else {
char.toUpperCase() // Converting the char to upper case
}
}
return output
}
Then you can use this extension function by the below code:
fun main(args: Array<String>) {
print("Hello World".reverseCaseOfString())
}
Output: hELLO wORLD
Default library support is not available till now to reverse the case of a string.
Here's my attempt at this, with the goal of keeping the code easy to read but also performant.
fun String.invertCase(): String {
val array = this.toCharArray()
this.forEachIndexed { index, char ->
when {
char.isUpperCase() -> array[index] = char.toLowerCase()
char.isLowerCase() -> array[index] = char.toUpperCase()
}
}
return String(array)
}
val input = "Hello World"
println(input.invertCase()) // hELLO wORLD
For me an elegant way is:
to create an extension function for Char:
fun Char.reverseCase(): Char = if (isUpperCase()) toLowerCase() else toUpperCase()
and then use it to create the extension for String:
fun String.reverseCase(): String = toCharArray().map { it.reverseCase() }.joinToString("")