Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to char in Kotlin?

Tags:

kotlin

fun main(args: Array<String>) {     val StringCharacter = "A"     val CharCharacter = StringCharacter.toChar()     println(CharCharacter) } 

I am unable to convert string A to char. I know that StringCharacter = 'A' makes it char but I need the conversion.

Thanks.

like image 835
Khayyam Avatar asked May 25 '17 16:05

Khayyam


People also ask

What is CharArray Kotlin?

Returns an element at the given index or null if the index is out of bounds of this array. fun CharArray.


1 Answers

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) 
like image 174
mfulton26 Avatar answered Sep 21 '22 23:09

mfulton26