Home » Scala programs » Scala string programs

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

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

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 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





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.