scala 拆分字符串翻转
A string is a collection that stores multiple characters, it is an immutable sequence which cannot be changed.
字符串是存储多个字符的集合,它是不可更改的不可更改的序列。
分割字符串 (Splitting a string)
In Scala, using the split() method one can split the string in an array based on the required separator like commas, spaces, line-breaks, symbols or any regular expression.
在Scala中,使用split()方法可以根据所需的分隔符(例如逗号,空格,换行符,符号或任何正则表达式)将字符串拆分为数组。
Syntax:
句法:
string.split("saperator")
程序在Scala中分割字符串 (Program to split a string in Scala)
object MyClass {
def main(args: Array[String]) {
val string = "Hello! Welcome to includeHelp..."
println(string)
val stringContents = string.split(" ")
println("Content of the string are: ")
for(i <- 0 to stringContents.length-1)
println(stringContents(i))
}
}
Output
输出量
Hello! Welcome to includeHelp...
Content of the string are:
Hello!
Welcome
to
includeHelp...
This method is useful when we are working with data that are encoded in a string like URL-encoded string, multiline data from servers, etc where the string need to be split to extract information. One major type is when data comes in the form of CSV (comma-separated value) strings which is most common and needs each value to be separated from the string.
当我们使用以字符串编码的数据(例如URL编码的字符串,来自服务器的多行数据)等需要对字符串进行拆分以提取信息时,此方法很有用。 一种主要类型是当数据以CSV(逗号分隔值)字符串的形式出现时,这是最常见的字符串,需要将每个值与字符串分开。
Let's see how to,
让我们看看如何
程序使用拆分方法拆分CSV字符串 (Program to split a CSV string using split method)
object MyClass {
def main(args: Array[String]) {
val CSVstring = "ThunderBird350 , S1000RR, Iron883, StreetTripleRS"
println(CSVstring)
val stringContents = CSVstring.split(", ")
println("Content of the string are: ")
for(i <- 0 to stringContents.length-1)
println(stringContents(i))
}
}
Output
输出量
ThunderBird350 , S1000RR, Iron883, StreetTripleRS
Content of the string are:
ThunderBird350
S1000RR
Iron883
StreetTripleRS
使用正则表达式分割字符串 (Splitting String using Regular Expressions)
In the split method, a regular expression(regex) can also be used as a separator to split strings.
在split方法中,正则表达式(regex)也可用作分隔符以分隔字符串。
object MyClass {
def main(args: Array[String]) {
val string = "1C 2C++ 3Java"
println(string)
val stringContents = string.split("\\d+")
println("Content of the string are: ")
for(i <- 0 to stringContents.length-1)
println(stringContents(i))
}
}
Output
输出量
1C 2C++ 3Java
Content of the string are: C
C++
Java
Here, we have separated the string using the regex \\d+ which considers any digit. In our string, the function will split every time a digit is encountered.
在这里,我们使用考虑任何数字的正则表达式\\ d +分隔了字符串。 在我们的字符串中,该函数将在每次遇到数字时拆分。
翻译自: https://www.includehelp.com/scala/split-string.aspx
scala 拆分字符串翻转