Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string by a string in Scala

Tags:

In Ruby, I did:

"string1::string2".split("::") 

In Scala, I can't find how to split using a string, not a single character.

like image 774
Félix Saparelli Avatar asked Apr 02 '11 10:04

Félix Saparelli


People also ask

How to split string in Scala?

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.

How do you split a string?

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.

What does split do in Scala?

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?

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.


2 Answers

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) 
like image 170
Janx Avatar answered Oct 03 '22 20:10

Janx


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").

like image 37
Moritz Avatar answered Oct 03 '22 22:10

Moritz