scala 字符串数组
Scala array is a collection of elements of the same data type. The data type can be string also, this is a string array.
Scala数组是相同数据类型的元素的集合。 数据类型也可以是字符串,这是一个字符串数组。
array = {"Hello!", "IncludeHelp", "Scala"}
在Scala中创建字符串数组 (Creating a string array in Scala)
You can initialize an array using the Array keyword. To know more about creating a Scala array, read: Scala Arrays
您可以使用Array关键字初始化数组。 要了解有关创建Scala数组的更多信息,请阅读: Scala Arrays
There are multiple ways to create a string array in Scala.
在Scala中有多种创建字符串数组的方法。
Method 1:
方法1:
If you know all elements of the array in advance, you can initialize the Scala array in the following manner.
如果您事先知道数组的所有元素,则可以按照以下方式初始化Scala数组。
val arr_name = Array(element1, element2, ...)
Program:
程序:
object myObject
{
def main(args:Array[String])
{
val colors = Array("Red", "Blue", "Black", "Green")
println("This is an array of string :")
for(i <- 0 to colors.length-1){
println(colors(i))
}
}
}
Output
输出量
This is an array of string :
Red
Blue
Black
Green
Method 2:
方法2:
If you don't know the elements of the string in advance but know the number of elements present in the array, then we will create an empty array of definite size first then feed elements to it.
如果您不事先知道字符串的元素,但是知道数组中存在的元素数量,那么我们将首先创建一个确定大小的空数组,然后将元素馈入其中。
val arr_name = new Array[String](number_of_elements)
Program:
程序:
object myObject
{
def main(args:Array[String])
{
val colors = new Array[String](3)
colors(0) = "Red"
colors(1) = "Blue"
colors(2) = "Black"
println("This is an array of string :")
for(i <- 0 to colors.length-1){
println("colors("+i+") : "+colors(i))
}
}
}
Output
输出量
This is an array of string :
colors(0) : Red
colors(1) : Blue
colors(2) : Black
在Scala中创建可变字符串数组 (Creating Mutable Strings Array in Scala)
You can create a string array even when you do not know the size and element of the array. For this, we will create a mutable string. This mutable string is created using
即使不知道数组的大小和元素,也可以创建字符串数组。 为此,我们将创建一个可变字符串。 该可变字符串是使用以下命令创建的
ArrayBuffer class whereas others were created using Array class.
ArrayBuffer类,而其他类是使用Array类创建的。
To create a mutable string we need to import mutable.ArrayBuffer in your program using,
要创建可变字符串,我们需要使用以下命令在您的程序中导入mutable.ArrayBuffer :
import scala.collection.mutable.ArrayBuffer
Program:
程序:
import scala.collection.mutable.ArrayBuffer
object myObject
{
def main(args:Array[String])
{
val colors = new ArrayBuffer[String]()
colors += "Red"
colors += "Blue"
colors += "Black"
colors += "Green"
println("Mutable string array:")
for(i <- 0 to colors.length-1){
println("colors("+i+") : " + colors(i))
}
}
}
Output
输出量
Mutable string array:
colors(0) : Red
colors(1) : Blue
colors(2) : Black
colors(3) : Green
翻译自: https://www.includehelp.com/scala/program-to-create-strings-array.aspx
scala 字符串数组