Q:

How to create a range of characters in Scala?

belongs to collection: Scala String Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program 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.

Program to create a range with interval

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')

Program 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 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to left-trim and right-trim strings in Scala?... >>
<< How to count the number of characters in a string ...