如何在不能转义的空白处分割字符串?

时间:2019-06-22 11:59:29

标签: string list haskell

我想将String分割成这样的非转义空格:

let s = "number\\ 1 number\\ 2 number\\ 3"


["number\\ 1", "number\\ 2", "number\\ 3"]

or even better

["number 1", "number 2", "number 3"]

我该怎么做?

尝试1:

let s = "number\\ 1 number\\ 2 number\\ 3"

splitWhitespace :: String -> [String]
splitWhitespcae s = splitOn " " s
-- returns ["number\\","1","number\\","2","number\\","3"]

concatBackslash :: [String] -> [String]
concatBackslash [] = []
concatBackslash (x : xx : xs) = case init x of
    "\\" -> (x ++ xx) : concatBackslash xs
    _ -> x : xx : concatBackslash x

但是由于某种原因,它会返回相同的列表。

尝试2:

splitOnWhitespace :: String -> [String]
splitOnWhitespace s = splitOn " " s

concatBackslash :: [String] -> [String]
concatBackslash [] = []
concatBackslash [x, xs] = case last x of
    '\\' -> [(init x) ++ xs]
    _ -> [x, xs]
concatBackslash (x : xx : xs) = case last x of
    '\\' -> concatBackslash (((init x) ++ xx) : xs)
    _ -> x: concatBackslash (xx : xs)

这是在@leftaroundabout的帮助下完成的,但是我没有空格就结束了。

> let s = "number\\ 1 number\\ 2 number\\ 3"
> concatBackslash $ splitOnWhitespace s
["number1","number2","number3"]

1 个答案:

答案 0 :(得分:2)

两个问题:

  • init为您提供所有除了字符串中的最后一个字符。但是,当您尝试与"\\"匹配时,确实是最后一个字符。因此,您实际上应该在case语句中使用last
  • 您确实需要init的地方是++将该元素与下一个元素一起使用。在这种情况下,您不希望保留结尾的\,而是保留所有结尾。