Reverse String

Hey guys. I’m very new to Kotlin and quite fresh with programming. I’m trying to create a Reverse string program so:

fun main(args: Array) {
var string1 = “Geeks”
var string2 = String()
var l = string1.length

for (i in string1.indices){
    string2[i] = string1.get(l-1)


Of course, the code is wrong so the questions are:

  1. Can I create an empty string but set the potential number of elements perhaps 5 that are empty and you will fill them out later?
  2. Can I create just an empty string and then add some elements?
  3. Can I create a string and then change its elements?

thank you for all your help

Strings are immutable in kotlin. You can’t change its contents after it is created. You have to either work with char array or StringBuilder. You can also look at buildSting library function.


That’s enough for me thank You.

Keep in mind that there is a function to do string reversal in kotlin stdlib: reversed - Kotlin Programming Language. You can look into its sources.


Can I do something like this with it?
var string2 = string1(String.reversed(): String)

val initialString = "abcd"
val reversedString = initialString.reversed()
val simpleReversedString = "abcd".reversed()

If you don’t understand, how those functions work. Please start with language documentation and tutorials.


thanks! Im going through documentation thanks for the advice

 var str = "Hello";
var length = str.length-1

for (index in str.indices)