Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string into equal-length substrings?

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.

like image 290
MartinStettner Avatar asked Sep 13 '10 10:09

MartinStettner


People also ask

How do you split a string into substrings in Python?

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.

How would you read the string and split into substrings?

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.

How do you split a string by length in python?

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.


2 Answers

scala> val grouped = "Thequickbrownfoxjumps".grouped(4).toList grouped: List[String] = List(Theq, uick, brow, nfox, jump, s) 
like image 172
michael.kebe Avatar answered Sep 18 '22 12:09

michael.kebe


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")   \***************************************************************************/ 
like image 29
xyz Avatar answered Sep 17 '22 12:09

xyz