- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin String - toCharArray() Function
The Kotlin string toCharArray() function is used to convert a string into a character array.
This function cannot manipulate the original string. This makes a copy of this string's characters with a new array, ensuring that the original string is immutable.
The resulting character array can be used directly for operations that require mutable sequences of characters.
Syntax
Following is the syntax of the Kotlin string toCharArray() function −
fun String.toCharArray(): CharArray
Parameters
This function does not accepts any parameters.
Return value
This function returns a new character array, where each element is a character from this string.
Example 1: Convert String to a charArray
Following is the basic example of converting a string to a character array using the toCharArray() −
fun main() {
val string = "tutorialspoint"
val charArray = string.toCharArray()
println(charArray.joinToString())
}
Output
Following is the output −
t, u, t, o, r, i, a, l, s, p, o, i, n, t
Example 2: Convert into charArray & Display Each
In this example, we convert the string to a character array and iterate through characters −
fun main() {
val string = "Kotlin"
val charArray = string.toCharArray()
for (char in charArray) {
println(char)
}
}
Output
Following is the output −
K o t l i n
Example 3
The below example converts a string to a char array. Since a char array is mutable, individual characters can be modified after conversion −
fun main() {
val text = "World"
val charArray = text.toCharArray()
// Change the first character
charArray[0] = 'H'
// Convert back to String
val newText = String(charArray)
println(newText)
}
Output
Following is the output −
Horld