[Haskell-cafe] split string into n parts

Rich Neswold rich.neswold at gmail.com
Mon Oct 23 16:35:23 EDT 2006


On 10/23/06, jim burton <jim at sdf-eu.org> wrote:
>
> I want to split a string into 5 parts of equal length, with the last fifth
> padded if necessary, but can't get it right

I got this:

fifths :: String -> String
fifths xs = let len = (length xs + 4) `div` 5
                    padded = take (len * 5) (xs ++ "     ")
                in unwords $ nth len padded
    where nth _ [] = []
              nth n xs = (take n xs) : (nth n $ drop n xs)

> *Main> fifths "IDOLIKETOBEBESIDETHESEASIDE"
> "IDOLI KETOBE BESIDE THESEA SIDEXX"
> *Main> fifths "12345"
> "1 23 45"

This gives the following results:

"IDOLIK ETOBEB ESIDET HESEAS IDE   "

and

"1 2 3 4 5"

But it also gives this result, which may or may not be correct for your
problem:

*Main> fifths "123456"
"12 34 56      "

-- 
Rich

AIM : rnezzy
ICQ : 174908475
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20061023/ea58948c/attachment-0001.htm


More information about the Haskell-Cafe mailing list