2

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 to String

var name = "ромка"
var charName = name.toLowerCase().toCharArray()
charName[0] = charName[0].toUpperCase()

name = charName.toString()

Results:

charName: {'Р', 'о', 'м', 'к', 'а'}

name == "[C@93ec54"

Screenshot

2
  • 1
    Do name = charName[0].toString() instead of charName.toString() as it is an Array and not a string Commented Jul 5, 2019 at 19:08
  • That'll just give you "Р" as that's the first character. Commented Jul 9, 2020 at 8:02

3 Answers 3

4
var name = "ромка"
val result = name.toLowerCase().capitalize()
Sign up to request clarification or add additional context in comments.

Comments

3
    var name = "ромка"
    var charName = name.toLowerCase().toCharArray()
    charName[0] = charName[0].toUpperCase()

    name = String(charName)

4 Comments

String(charName) it's working, but why? I have problem with toString()
@RomanShubenko Are you sure you are using a Kotlin String class?
Hmm, maybe no, maybe yes:)
To string on Arrays just returns a debug representation of the array as you've seen. To string is a property of all arrays, not one of char arrays designed to convert it back to a String.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.