Split a string by a chosen character in haskell

前端 未结 3 1487
北恋
北恋 2021-01-24 04:58

I\'m trying to split a string every time there is a chosen character. So if I receive \"1,2,3,4,5\", and my chosen character is \",\" the result is a l

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-24 05:22

    Basically this is a foldring job. So you may simply do like

    λ> foldr (\c (s:ss) -> if c == ',' then "":s:ss else (c:s):ss) [""] "1,2,3,42,5"
    ["1","2","3","42","5"]
    

    So;

    splitOn x = foldr (\c (s:ss) -> if c == x then "":s:ss else (c:s):ss) [""]
    

    However this will give us reasonable but perhaps not wanted results such as;

    λ> splitOn ',' ",1,2,3,42,5,"
    ["","1","2","3","42","5",""]
    

    In this particular case it might be nice to trim the unwanted characters off of the string in advance. In Haskell though, this functionality i guess conventionally gets the name

    dropAround :: (Char -> Bool) -> String -> String
    dropAround b = dropWhile b . dropWhileEnd b
    
    λ> dropAround (==',') ",1,2,3,42,5,"
    "1,2,3,42,5"
    

    accordingly;

    λ> splitOn (',') . dropAround (==',') $ ",1,2,3,42,5,"
    ["1","2","3","42","5"]
    

提交回复
热议问题