In Ruby, I did:
"string1::string2".split("::")
In Scala, I can't find how to split
using a string, not a single character.
The split() method in Scala is used to split the given string into an array of strings using the separator passed as parameter. You can alternatively limit the total number of elements of the array using limit.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
Split is used to divide the string into several parts containing inside an array because this function return us array as result. We can also limit our array elements by using the 'limit' parameter. Otherwise, it will just contain all the parameters from the string that has been spitted.
How do I split a string based on space but take quoted substrings as one word? \S* - followed by zero or more non-space characters.
The REPL is even easier than Stack Overflow. I just pasted your example as is.
Welcome to Scala version 2.8.1.final (Java HotSpot Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.
scala> "string1::string2".split("::") res0: Array[java.lang.String] = Array(string1, string2)
In your example it does not make a difference, but the String#split
method in Scala actually takes a String
that represents a regular expression. So be sure to escape certain characters as needed, like e.g. in "a..b.c".split("""\.\.""")
or to make that fact more obvious you can call the split method on a RegEx
: """\.\.""".r.split("a..b.c")
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With