Home » 
        Scala
    
    How to create a range of characters as a Scala array?
    
    
    
    
        
            By IncludeHelp Last updated : October 20, 2024
        
    
    An array is a sequence of data elements of the same data type. We can also make a char array, and in this tutorial, we will create a character array. 
    The range is a way to create a sequence of elements from a starting element to an ending element.  this can be used to create a sequence of numbers as well as characters. 
    Creating a sequence of characters as a Scala array
    We can create a sequence of characters as a Scala array using Scala method along with their range keyword. To the range, we will pass the starting and ending characters of the sequence.  This will give out a sequence with elements from starting to ending characters. 
    For example, if we pass 's' and 'x' to the range it will return 's, t, u, v, w, x'.  And we will store this to an array of characters. 
    There are two ways  to assign a range to an array: 
    
        - Using ().toArray
 
        - Using array.range()
 
    
    1. Using ().toArray
    The toArray() method is used to convert the given object to the array. This will create an array using the data type of the first occurrence datatype. 
Example
object MyClass {
    def main(args: Array[String]) {
        var arr = ('s' to 'x').toArray
        arr.foreach { println }
    }
}
Output
s
t
u
v
w
x
    2. Using array.range()
    The output of array.range() is also the same as the toarray(), but is a different method to do the work.
Example
object MyClass {
    def main(args: Array[String]) {
        val arr = Array.range('a', 'e')  
        arr.foreach { println }
    }
}
Output
97
98
99
100
    
    It will give out the ASCII value of the characters.  Now, you can use can them to characters explicitly to given char output. 
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement