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)
    l--
}
print(string2)

}

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.

3 Likes

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.

2 Likes

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

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

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

2 Likes

thanks! Im going through documentation thanks for the advice

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

for (index in str.indices)
{
print(str[length-index])
}