newbie question! Hello! please tell me how can I a...
# getting-started
c
newbie question! Hello! please tell me how can I add char to string?
m
hi, you should be able to use the plus operator
Copy code
val someString = "abc"
val someChar = 'c'
val result = someString + someChar
//or better, string template
val result = "$someString$someChar"
c
but if i need use something like someString +=someChar? add char to existing string
m
then you need to declare the existing string as mutable -
var
, not
val
c
tnx, i thought i need to use something like
stringbuilder
for this
k
If you're going to do this often (eg in a loop) it would be better to use a stringbuilder indeed.
t
Strings in Kotlin are immutable sequences of characters, just like in Java. Adding a new character to a string (with
+
or using the string template syntax) always results in a new String instance being created. If you need a mutable sequence of characters, you should use
StringBuilder
.