A CharSequence (e.g. String) can be empty, have a single character, or have more than one character.
If you want a function that "returns the single character, or throws an exception if the char sequence is empty or has more than one character" then you want single:
val string = "A"
val char = string.single()
println(char)
And if you want to call single by a different name you can create your own extension function to do so:
fun CharSequence.toChar() = single()
Usage:
val string = "A"
val char = string.toChar()
println(char)
Answer from mfulton26 on Stack OverflowA CharSequence (e.g. String) can be empty, have a single character, or have more than one character.
If you want a function that "returns the single character, or throws an exception if the char sequence is empty or has more than one character" then you want single:
val string = "A"
val char = string.single()
println(char)
And if you want to call single by a different name you can create your own extension function to do so:
fun CharSequence.toChar() = single()
Usage:
val string = "A"
val char = string.toChar()
println(char)
You cannot convert a String to a Char, because a String is an array of Chars. Instead, select a Char from the String:
val string = "A"
val character = string.get(0) // Or string[0]
println(character)
How do I split a string into single characters and put them into a list?
CharArray.concatToString() vs. CharArray.joinToString("") - Support - Kotlin Discussions
How can I convert CharArray / Array<Char> to a String? - Stack Overflow
String to Array - Kotlin Discussions
Hallo fellow Kotliners,
I started learning Kotlin and I wanted to do a littler excersise.
I want to split "banana" into single characters and put them into a list.
Input : "banana"
Output: [ 'b', 'a', 'n', 'a', 'n', 'a' ]
I tried googling around an looking stuff up, but it did not work out.
Can you please help me solving this?
you can simply using Array#joinToString:
val result: String = chars.joinToString("");
OR convert chars to CharArray:
val result: String = String(chars.toCharArray());
OR declaring a primitive CharArray by using charArrayOf:
val chars = charArrayOf('A', 'B', 'C');
val result: String = String(chars);
You can also use concatToString.
val chars = "ABC".toCharArray()
val result = chars.concatToString()
toCharArray() toByteArray() // using charser = Charsets.UTF-32
These wont work. Char is just 16 bit. Unicode might be more than that.
val str = “இன்று”
It has just three unicode characters…
I tried to separate the characters using
str.codePoints().toArray().size Returns 5
So i think contains surrogate pair. I cant find enough details in the document regarding surrogate pair or codePoints
How do i take each unicode character from that string and store it in an array?
I tried to find the high and low surrogates using isHighSurrogate() ( toCharArray() )
It is not working. Is it a bug?