Kotlin charArrayOf()
The Kotlin charArrayOf() function is used to create an array of characters with the specified characters as elements.
In this tutorial, we shall learn the syntax and usage of charArrayOf() function with examples.
Syntax
The syntax of charArrayOf() function is
fun charArrayOf(vararg elements: Char): CharArray
where
Parameter | Description |
---|---|
elements | The characters to be included in the array. |
Return Value
The charArrayOf() function returns a CharArray
object containing given characters.
Example 1: Basic Usage of charArrayOf()
In this example, we shall use the charArrayOf() function to create an array of characters representing the word “Kotlin”, and then print each character in the array to output using a For loop.
Kotlin Program
fun main() {
val wordArray = charArrayOf('a', 'p', 'p', 'l', 'e')
for (char in wordArray) {
print(char)
}
}
Output
apple
Example 2: Creating a CharArray with Special Characters using charArrayOf()
In this example, we shall use the charArrayOf() function to create an array of characters with special symbols and then prints each character in the array.
Kotlin Program
fun main() {
val specialChars = charArrayOf('!', '@', '#', '$', '%')
for (char in specialChars) {
print(char)
}
}
Output
!@#$%
Summary
In this tutorial, we shall seen about charArrayOf() function, its syntax, and how to use this function in the creation of character arrays by allowing you to specify the characters directly in the function call.