Kotlin program to change uppercase and lowercase of a string

Published by admin on

Kotlin change string uppercase and lowercase

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.

Categories: kotlin


Plaban · November 7, 2019 at 8:22 am

How to save the output in a variable for using latter in the code?

    admin · November 8, 2019 at 4:00 am

    when block can return result. For example :

    val result = when {
    number % 2 == 0 -> “even”
    else -> “odd”

    admin · November 8, 2019 at 4:09 am

    updated the post

Leave a Reply

Your email address will not be published. Required fields are marked *