Kotlin program to change uppercase and lowercase of a string

Introduction :

This is a simple Kotlin sample program that will show you how to check if a character is lowercase or uppercase and how to convert it to a lowercase or uppercase character.

  1. One string is given, we will scan each character of the string one by one.

  2. For each character, check if it is lowercase. If lowercase, convert it to uppercase.

  3. If the character is uppercase, convert it to lowercase.

  4. To check lowercase, we will use isLowerCase and to check uppercase, we will use isUpperCase methods.

  5. To convert a letter to lowercase, toLowerCase and to check lowercase, we will use isLowerCase methods.

  6. We will use one for loop to scan the string character by character. And, one when block to test the character.

Kotlin Program :

fun main() {
    val helloWorld = "Hello World !! Let's count 1,2,3..."
    for (c in helloWorld) {
        when {
            c.isLowerCase() -> print(c.toUpperCase())
            c.isUpperCase() -> print(c.toLowerCase())
            else -> print(c)
        }
    }
}

If you will run this program, it will print the following output :

hELLO wORLD !! lET'S COUNT 1,2,3...

So, the lowercase letters are converted to uppercase, uppercase letters are converted to lowercase but numbers and special characters are kept same.

Save the string for later use :

fun main() {
    val helloWorld = "Hello World !! Let's count 1,2,3..."
    var modifiedString = ""

    for (c in helloWorld) {
        modifiedString += when {
            c.isLowerCase() -> c.toUpperCase()
            c.isUpperCase() -> c.toLowerCase()
            else -> c
        }
    }

    print("Modified string : $modifiedString")
}

It will store the string in the variable modifiedString. You can use it later in your program.