Home »
Scala
Scala String toCharArray() Method
By IncludeHelp Last updated : October 21, 2024
Description and Usage
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 :