gpt4 book ai didi

string - Haskell 提取字符串中的子字符串

转载 作者:行者123 更新时间:2023-12-05 00:27:04 24 4
gpt4 key购买 nike

我的目标是找到子字符串在字符串中存在的次数。
我要查找的子字符串的类型为“[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))

如果有人可以启发我如何在字符串中搜索子字符串
或者如何解析给定子字符串的字符串,将不胜感激。

最佳答案

我只会使用正则表达式,然后像这样写:

import Text.Regex.Posix

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..."


-- references counts the number of references in the input string
references :: String -> Int
references str = str =~ "\\[[0-9]*\\]"

main = putStrLn $ show $ references txt -- outputs 3

关于string - Haskell 提取字符串中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21298098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com