Scala String toCharArray() Method with Example

Here, we will learn about the toCharArray() method in Scala. The method is used to convert string to character array. We will see its working, syntax and examples.
Submitted by Shivang Yadav, on January 30, 2021

String is an immutable collection that stores sequences of characters.

String toCharArray() Method

The toCharArray() method defined on string is used to convert the given string to a character array (charArray).

Syntax:

string_Name.toCharArray()

Parameters: The method is a parameter-less method i.e. it does not accept any parameter.

Return Value: It returns a charArray.

Example 1:

object MyClass {
    def main(args: Array[String]) {
        val myString = "scala Programming Language"
        println("The string is '" + myString + "'")
        
        val char_array = myString.toCharArray()
        println(char_array)
        
        println("Printing the char_array : ")
        for(i <- char_array)
            print(i + " ")
    }
}

Output:

The string is 'scala Programming Language'
[C@61e45f87
Printing the char_array : 
s c a l a   P r o g r a m m i n g   L a n g u a g e

In the above code, we have accessed charArray using its name which returns [C@61e45f87 which is the location of the first character. And to print we need to print it character by character.

Example 2:

object MyClass {
    def main(args: Array[String]) {
        val myString = ""
        println("The string is '" + myString + "'")
        
        val char_array = myString.toCharArray()
        println(char_array)
        
        println("Printing the char_array : ")
        for(i <- char_array)
            print(i + " ")
    }
}

Output:

The string is ''
[C@61e45f87
Printing the char_array : 


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.