Kotlin Program to Reverse a String

In this blog post, we will learn how to write a Kotlin program to reverse a String.

String manipulation is a fundamental aspect of programming, and one common task is to reverse a given string. In this blog post, we will explore a Kotlin program that efficiently reverses a string. We will walk through the program step by step, explaining the logic behind it. 

Kotlin Program to Reverse a String

To reverse a string in Kotlin, we can follow a straightforward approach. Let's dive into the code:
fun reverseString(input: String): String {
    val charArray = input.toCharArray()
    var left = 0
    var right = charArray.size - 1

    while (left < right) {
        val temp = charArray[left]
        charArray[left] = charArray[right]
        charArray[right] = temp
        left++
        right--
    }

    return String(charArray)
}

fun main() {
    val input = "Hello, World!"
    val reversedString = reverseString(input)
    println("Original String: $input")
    println("Reversed String: $reversedString")
}
Output:
Original String: Hello, World!
Reversed String: !dlroW ,olleH
Explanation:
The reverseString() function takes a string input as input and returns the reversed string. 

Inside the reverseString() function, we convert the input string into a character array using the toCharArray() method. This allows us to manipulate the characters of the string. 

We initialize two pointers, left and right, to the start and end of the character array, respectively. 

Using a while loop, we swap the characters at the left and right positions until the pointers meet in the middle of the array. We do this by storing the character at left in a temporary variable, swapping the characters, incrementing left and decrementing right

Finally, we convert the character array back to a string using the String(charArray) constructor and return the reversed string. 

In the main() function, we create a sample input string (val input = "Hello, World!") and call the reverseString() function with this input. The original and reversed strings are then printed to the console using println()

Conclusion

In this blog post, we have discussed a Kotlin program that efficiently reverses a given string. By utilizing character manipulation and swapping, we achieve the desired result. Understanding this program equips you with the necessary skills to reverse strings and solve similar string manipulation tasks in Kotlin. 

Feel free to explore and modify the code to suit your specific needs. Reversing strings is a common programming requirement, and this program demonstrates an optimal solution. Happy coding!

Comments