Kotlin program to convert one string to character array

Introduction :

In this kotlin tutorial, we will learn how to convert one string to a character array. Kotlin provides one method called toCharArray that can be used to convert one string to character array.

This method is currently marked as experimental Library API.

toCharArray :

Definition :

str.toCharArray() : CharArray

It returns a character array that contains the characters of the string.

Let’s take a look at the below example :

fun main() {
    val givenStr = "Hello World"
    val charArray = givenStr.toCharArray()

    println(charArray.contentToString())
}

It will print :

[H, e, l, l, o,  , W, o, r, l, d]

toCharArray(startIndex, endIndex) :

We can also pass the start and end indices of the string to get one character array of a substring. This method is defined as below :

str.toCharArray(startIndex: Int, endIndex: Int): CharArray

Here, startIndex is the start index and endIndex is the end index. startIndex is 0 by default and endIndex is size of the string by default. It throws IndexOutOfBoundsException for invalid indices and IllegalArgumentException if startIndex is greater than endIndex.

For example :

fun main() {
    val givenStr = "Hello World"
    val charArray = givenStr.toCharArray(startIndex = 0,endIndex = 4)

    println(charArray.contentToString())
}

It will print :

[H, e, l, l, o]

toCharArray(destination, destinationOffset, startIndex, endIndex) :

This method can be used to copy into a different array.

It is defined as below :

str.toCharArray(destination: CharArray, destinationOffset: Int, startIndex: Int, endIndex: Int): CharArray

Here, the characters will be copied to the destination array starting from startIndex to endIndex. destinationOffset is the offset to use in the destination array. It returns the new array.

It can also throw IndexOutOfBoundException or IllegalArgumentException.

For example :

fun main() {
    val givenStr = "Hello World"
    val destinationArray = charArrayOf('a','b','c','d')
    givenStr.toCharArray(destinationArray,1,0,3)

    println(destinationArray.contentToString())
}

It will print :

[a, H, e, l]

Similar tutorials :