Home » Scala language

How to create a range of characters as a Scala array?

Multi-dimensional array in Scala is used to store data in matrix form i.e. in the form of multiple row and column. In this Scala tutorial, we will learn about multi-dimensional arrays in Scala and methods to create them with working code.
Submitted by Shivang Yadav, on July 28, 2019

For storing a sequence of characters in an array, there is a quick trick that can be used in Scala programming. In this tutorial, we will show you a working example of how to initialize a character array with a range of characters?

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:

  1. Using ().toArray
  2. Using array.range()

1) Creating a sequence of characters as a Scala array 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.

Program:

object MyClass {
    def main(args: Array[String]) {
        var arr = ('s' to 'x').toArray
        arr.foreach { println }
    }
}

Output

s
t
u
v
w
x

2) Creating a sequence of characters as a Scala array using array.range()

The output of array.range() is also the same as the toarray(), but is a different method to do the work.

Program:

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.







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.