Khayyam
Khayyam

Reputation: 733

How to convert string to char in 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.

Upvotes: 28

Views: 26536

Answers (3)

Avijit Karmakar
Avijit Karmakar

Reputation: 9388

A String cannot be converted to a Char because String is an array of chars. You can convert a String to an Char array or you can get a character from that String.

Example:

val a = "Hello"
val ch1 = a.toCharArray()[0]   // output: H 
val ch2 = a[0]    // output: H

Upvotes: 5

mfulton26
mfulton26

Reputation: 31214

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)

Upvotes: 41

nhaarman
nhaarman

Reputation: 100358

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)

Upvotes: 7

Related Questions