How to create a range of characters in Scala?

Here, we are going to learn how to create a range of characters in Scala programming language?
Submitted by Shivang Yadav, on April 24, 2020 [Last updated : March 10, 2023]

Scala – Creating a range of characters

The range is a set of data from a lower value to a larger value. In Scala, we have an easy method to create a range using to keyword.

Syntax

    startchar to endchar

Example 1: Scala code to create a range of characters

object myObject {    
    def main(args: Array[String]) {
        val string = ('i' to 'z').toArray
        for(i <- 0 to string.length-1)
        print(string(i) + " ")
    }
}

Output

i j k l m n o p q r s t u v w x y z 

You can also choose the value to be incremented, i.e. you can skip any number of elements while creating this range.

Example 2: Scala code to create a range of characters

object myObject {    
    def main(args: Array[String]) {
        val string = ('A' to 'K' by 3).toArray
        for(i <- 0 to string.length-1)
        print(string(i) + " ")
    }
}

Output

A D G J 

This range of characters is converted to the array here, we can convert the same to List, vectors, etc using toList and toVector methods respectively.

Create ASCII Range

You can also create a range of ASCII of the value of character within the given range.

Syntax

    array.range('startChar' , 'endChar')

Scala code to create a range of ASCII values

object myObject {   
    def main(args: Array[String]) {
        val ASCIIrange = Array.range('A', 'K')
        for(i <- 0 to ASCIIrange.length-1)
            print(ASCIIrange(i) + " ")
    }
}

Output

65 66 67 68 69 70 71 72 73 74 

Scala String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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