29
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.

3
  • What doesn't work in your code snippet? Commented May 25, 2017 at 16:23
  • 1
    Unresolved reference: toChar() Commented May 25, 2017 at 16:26
  • val c = StringCharacter[0] you will get StringIndexOutOfBoundsException is String is empty Commented May 25, 2017 at 18:17

3 Answers 3

41

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)
Sign up to request clarification or add additional context in comments.

Comments

7

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)

1 Comment

get(0) and [0] is the same in kotlin, so you can get the first character with string[0] which is more idiomatic
5

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

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.