Reputation: 509
Good day, I'm starter and I have some problem:
I want to convert this "ромка"
or this "роМка"
to "Ромка"
using this code. My code is OK. I have problem with toString()
.
Rewrite string using only one first upper char. Problem with converting
charArray
toString
var name = "ромка"
var charName = name.toLowerCase().toCharArray()
charName[0] = charName[0].toUpperCase()
name = charName.toString()
Results:
charName: {'Р', 'о', 'м', 'к', 'а'}
name == "[C@93ec54"
Upvotes: 2
Views: 1011
Reputation: 23105
The reason why toString()
works this way is that in run time Kotlin arrays are represented with JVM array types, so for example CharArray
is char[]
in run time. Those JVM types do not provide meaningful implementations of toString
, equals
, and hashCode
methods.
Instead Kotlin provides the extension functions contentToString
, contentEquals
and contentHashCode
for arrays. These functions are implemented so as if the array was a list, for example contentToString
would return [Р, о, м, к, а]
for the array from the question.
However, if you want to concatenate all chars in a char array to a string, you should use another function: either String(CharArray)
available in Kotlin/JVM, or the experimental extension CharArray.concatToString()
available for all platforms since Kotlin 1.3.40.
Finally, if your task is to capitalize the first character, then capitalize
function will do all these manipulations for you, as @Francesc has suggested in his answer.
Upvotes: 1
Reputation: 236
var name = "ромка"
var charName = name.toLowerCase().toCharArray()
charName[0] = charName[0].toUpperCase()
name = String(charName)
Upvotes: 3