What is the best way to split a string by a delimiter functionally?

后端 未结 9 1778
死守一世寂寞
死守一世寂寞 2020-12-29 22:11

I tried to write the program in Haskell that will take a string of integer numbers delimitated by comma, convert it to list of integer numbers and increment each number by 1

相关标签:
9条回答
  • 2020-12-29 22:53

    Doesn't Data.List.Split.splitOn do this?

    0 讨论(0)
  • 2020-12-29 22:54
    splitBy delimiter = foldr f [[]] 
                where f c l@(x:xs) | c == delimiter = []:l
                                 | otherwise = (c:x):xs
    

    Edit: not by the original author, but below is a more (overly?) verbose, and less flexible version (specific to Char/String) to help clarify how this works. Use the above version because it works on any list of a type with an Eq instance.

    splitBy :: Char -> String -> [String]
    splitBy _ "" = [];
    splitBy delimiterChar inputString = foldr f [""] inputString
      where f :: Char -> [String] -> [String]
            f currentChar allStrings@(partialString:handledStrings)
              | currentChar == delimiterChar = "":allStrings -- start a new partial string at the head of the list of all strings
              | otherwise = (currentChar:partialString):handledStrings -- add the current char to the partial string
    
    -- input:       "a,b,c"
    -- fold steps:
    -- first step:  'c' -> [""] -> ["c"]
    -- second step: ',' -> ["c"] -> ["","c"]
    -- third step:  'b' -> ["","c"] -> ["b","c"]
    -- fourth step: ',' -> ["b","c"] -> ["","b","c"]
    -- fifth step:  'a' -> ["","b","c"] -> ["a","b","c"]
    
    0 讨论(0)
  • 2020-12-29 22:59

    This code works fine use:- split "Your string" [] and replace ',' with any delimiter

    split [] t = [t]
    split (a:l) t = if a==',' then (t:split l []) else split l (t++[a])
    
    0 讨论(0)
提交回复
热议问题