Created
January 6, 2024 07:23
-
-
Save mzennis/8f7ae707e1288d0ddd8d08763a299d9c to your computer and use it in GitHub Desktop.
Unnecessary toUpperCase() and toLowerCase() functions with Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() { | |
print("Enter your name: ") | |
val input = readLine() | |
if (input != null) { | |
println("Name: $input") | |
// print the result using our 'String.toUpperCase()' func | |
println("toUpperCase : ${input.toUpperCase()}") | |
// print the result using our 'String.toLowerCase()' func | |
println("toLowerCase : ${input.toLowerCase()}") | |
} | |
} | |
fun String.toUpperCase(): String { | |
// we will collect the output in 'output' variable | |
// because we need to modify this variable on runtime, we define it as 'var' | |
var output = "" | |
// first, we'll iterate the String, bcs basically a String is an array of char | |
for (i in this) { | |
// if the char is a lowercase letter | |
if (i in 'a'..'z') { | |
// then we will run our formula | |
output += (i.code - 32).toChar() | |
} else { | |
// else, we assume this char was already in uppercase letter | |
output += i | |
} | |
} | |
return output | |
} | |
fun String.toLowerCase(): String { | |
var output = "" | |
for (i in this) { | |
// now we check whether the char is an uppercase letter | |
if (i in 'A'..'Z') { | |
// then we will run our formula | |
output += (i.code + 32).toChar() | |
} else { | |
// else, we assume this char was already in lowercase letter | |
output += i | |
} | |
} | |
return output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment