English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to convert characters (char) and strings (string) to each other in Kotlin.
fun main(args: Array<String>) { val ch = 'c' val st = Character.toString(ch) //Or // st = String.valueOf(ch); println("String: $st") }
When running the program, the output is:
String: c
In the above program, we store a character in the variable ch. We use the Character class's toString() method to convert the char character to a string st.
Additionally, we can also use the String's valueOf() method for the conversion. However, both are the same internally.
If you have a char array instead of just a single char, you can easily convert it to a string using the following string method
fun main(args: Array<String>) { val ch = charArrayOf('a', 'e', 'i', 'o', 'u') val st = String(ch) val st2 = String(ch) println(st) println(st)2) }
When running the program, the output is:
aeiou aeiou
In the above program, we have a char array ch containing vowels. We use the String's valueOf() method again to convert the character array to a String.
We can also use the string constructor, which takes a character array ch as a parameter for conversion.
We can also use the string method toCharArray() to convert a string to a char array (not a single char).
import java.util.Arrays fun main(args: Array<String>) { val st = "This is great" val chars = st.toCharArray() println(Arrays.toString(chars)) }
When running the program, the output is:
[T, h, i, s, , i, s, , g, r, e, a, t]
In the above program, we stored a string in the variable st. We used the string.toCharArray() method to convert the string into a character array stored in char format.
Then, we use the Arrays.toString() method to print the elements of the char array in the form of chars.
This is the equivalent Java code:Java Program to Convert char and String Interchangeably