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'
[[email protected]
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 [[email protected] 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 ''
[[email protected]
Printing the char_array : 




Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.