Append a character to a String in Kotlin
This article explores different ways to append a character at the end of a String in Kotlin. Since strings are immutable in Kotlin, the solution creates a new String instance.
1. Using plus() function
A simple solution to append characters to the end of a String is using the + (or +=) operator.
|
1 2 3 4 5 6 7 |
fun main() { var str = "C" val c = '#' str = str + c println(str) // C# } |
Alternatively, we can use the plus() function to concatenate a char with the given string.
|
1 2 3 4 5 6 7 |
fun main() { var str = "C" val c = '#' str = str.plus(c) println(str) // C# } |
2. Using String templates
Another concise solution to append a character to a string is with String templates. A template expression starts with a dollar sign ($) and consists of a name or an expression:
|
1 2 3 4 5 6 7 |
fun main() { var str = "C" val c = '#' str = "$c$str" println(str) // C# } |
3. Using String builder
The idea here is to convert the string to a String builder and call its append() function to append a character. This logic would translate to the following code:
|
1 2 3 4 5 6 7 |
fun main() { var str = "C" val c = '+' str = StringBuilder(str).append(c).append(c).toString() println(str) // C++ } |
4. Using String.format() function
Finally, we can use the String.format() function to concatenate a character with a string. This is demonstrated below:
|
1 2 3 4 5 6 7 |
fun main() { var str = "C" val c = '#' str = String.format("%s%c", str, c) println(str) // C# } |
That’s all about appending a character to the end of a String in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)