Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "prepend" a Char to a String in Kotlin

Tags:

How in Kotlin can I prepend a Char to a String?

e.g.

fun main(args: Array<String>) {   val char = 'H'   val string = "ello World"   val appendingWorks = string + char //but not what I want...   //val prependingFails = char + string //no .plus(str:String) version   val prependingWorkaround1 = char.toString() + string   val prependingWorkaround2 = "" + char + string   val prependingWorkaround3 = String(charArray(char)) + string  } 

When trying to call + (e.g. plus) on Char, there is no version that accepts a String on the right, so therefore 'H' + "ello World" doesn't compile

The first workaround might be good enough but it's a regression for me from what works in Java: String test = 'H' + "ello World"; (compiles fine...)

I also don't like the last workaround, at least in the java.lang.String I have a constructor that accepts a single char, or I can use java.lang.Character.toString(char c). Is there an elegant way in Kotlin to do so?

Was this discussed before (adding a plus(str:String) overload to the Char object?)

like image 480
Eran Medan Avatar asked Dec 29 '13 04:12

Eran Medan


People also ask

How do you add a character to a string in Kotlin?

A simple solution to append characters to the end of a String is using the + (or += ) operator. Alternatively, we can use the plus() function to concatenate a char with the given string.

How do you replace a character in a string in Kotlin?

Strings are immutable in Kotlin. That means their values cannot be changed once created. To replace the character in a string, you will need to create a new string with the replaced character.

How do I append in Kotlin?

There are different ways to concatenate strings in Kotlin. For example, we can use the $ operator or we can use the append() function or we can simply use the "+" operator to join two strings.

What is Kotlin string interpolation?

What Is String Interpolation in Kotlin? A string interpolation or interpolation expression is a piece of code that is evaluated and returns a string as a result. In Kotlin, string interpolation allows us to concatenate constant strings efficiently and variables to create another string.


1 Answers

What about using string templates, like this:

val prepended = "$char$string" 
like image 182
SkyrawrCode Avatar answered Oct 04 '22 11:10

SkyrawrCode