[Haskell-cafe] How to split this string.

Anupam Jain ajnsit at gmail.com
Mon Jan 2 11:42:33 CET 2012

On Mon, Jan 2, 2012 at 3:14 PM, max <mk at mtw.ru> wrote:
> I want to write a function whose behavior is as follows:
> foo "string1\nstring2\r\nstring3\nstring4" = ["string1",
> "string2\r\nstring3", "string4"]
> Note the sequence "\r\n", which is ignored. How can I do this?

Here's a simple way (may not be the most efficient) -

import Data.List (isSuffixOf)

split = reverse . foldl f [] . lines
    f [] w = [w]
    f (x:xs) w = if "\r" `isSuffixOf` x then ((x++"\n"++w):xs) else (w:x:xs)

Testing -

ghci> split "ab\r\ncd\nefgh\nhijk"

-- Anupam

More information about the Haskell-Cafe mailing list