【发布时间】:2014-02-13 09:45:08
【问题描述】:
我的目标是找出子字符串在字符串中存在的次数。 我要查找的子字符串类型为“[n]”,其中 n 可以是任何变量。
我的尝试涉及使用 words 函数拆分字符串, 如果字符串的“头”是“[”,则创建一个新的字符串列表 同一字符串的“最后一个”是“]”
我遇到的问题是我输入了一个字符串,当使用它进行拆分时 功能词,创建了一个看起来像这样“[2]”的字符串 现在,我仍然希望这算作“[n]”类型的出现
一个例子是我想要这个字符串,
asdf[1]jkl[2]asdf[1]jkl
返回 3。
这是我的代码:
-- String that will be tested on references function
txt :: String
txt = "[1] and [2] both feature characters who will do whatever it takes to " ++
"get to their goal, and in the end the thing they want the most ends " ++
"up destroying them. In case of [2], this is a whale..."
-- Function that will take a list of Strings and return a list that contains
-- any String of the type [n], where n is an variable
ref :: [String] -> [String]
ref [] = []
ref xs = [x | x <- xs, head x == '[', last x == ']']
-- Function takes a text with references in the format [n] and returns
-- the total number of references.
-- Example : ghci> references txt -- -> 3
references :: String -> Integer
references txt = len (ref (words txt))
如果有人能告诉我如何在字符串中搜索子字符串 或如何解析给定子字符串的字符串,将不胜感激。
【问题讨论】:
标签: string parsing haskell substring extract