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 拆分字符串翻轉