Im looking for an elegant way in Scala to split a given string into substrings of fixed size (the last string in the sequence might be shorter).
So
split("Thequickbrownfoxjumps", 4)
should yield
["Theq","uick","brow","nfox","jump","s"]
Of course I could simply use a loop but there has to be a more elegant (functional style) solution.
Python split() Method Syntax When you need to split a string into substrings, you can use the split() method. In the above syntax: <string> is any valid Python string, sep is the separator that you'd like to split on.
Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.
The string splitting can be done in two ways: Slicing the given string based on the length of split. Converting the given string to a list with list(str) function, where characters of the string breakdown to form the the elements of a list.
scala> val grouped = "Thequickbrownfoxjumps".grouped(4).toList grouped: List[String] = List(Theq, uick, brow, nfox, jump, s)
Like this:
def splitString(xs: String, n: Int): List[String] = { if (xs.isEmpty) Nil else { val (ys, zs) = xs.splitAt(n) ys :: splitString(zs, n) } }
splitString("Thequickbrownfoxjumps", 4) /************************************Executing-Process**********************************\ ( ys , zs ) Theq uickbrownfoxjumps uick brownfoxjumps brow nfoxjumps nfox jumps jump s s "" ("".isEmpty // true) "" :: Nil ==> List("s") "jump" :: List("s") ==> List("jump", "s") "nfox" :: List("jump", "s") ==> List("nfox", "jump", "s") "brow" :: List("nfox", "jump", "s") ==> List("brow", "nfox", "jump", "s") "uick" :: List("brow", "nfox", "jump", "s") ==> List("uick", "brow", "nfox", "jump", "s") "Theq" :: List("uick", "brow", "nfox", "jump", "s") ==> List("Theq", "uick", "brow", "nfox", "jump", "s") \***************************************************************************/
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