string - Haskell:在没有 Data.List 包的情况下替换字符串中的子字符串
问题描述
我是 Haskell 的新手,我想知道如何用另一个词替换字符串中的预定词。到目前为止,这是我的代码,我知道我现在不能这样做:
treat :: String -> String
treat text = text
main::IO()
main = do argv <- getArgs
texte <- readFile "intputText"
print (separation text)
print ( treat text )
separation :: String -> [String]
separation [] = [""]
separation (c:cs) | c == "\Graph" = "Graphic : " : rest
| c == '}' = "" : rest
| c == '{' = "" : rest
| otherwise = (c : head rest) : tail rest
where rest = separation cs
所以基本上我知道我不能在第一个 c == "\Graph" 中放置一个字符串,所以我想知道如何将字符串文本中的每个单词 "\Graph" 基本上替换为 "Graphic"。
我希望能够在不导入任何包的情况下做到这一点。
如果有人可以帮助我,我将不胜感激。
非常感谢!
解决方案
replace :: String -> String -> String-> String
replace [] token repl = []
replace str@(s:ss) token@(t:tx) repl
-- check if first char of string equal to first char of token
| s == t = case validateToken token str of
Just list -> repl ++ replace list token repl
Nothing -> s : replace ss token repl
-- if not equal then continue recursion step
| otherwise = s: replace ss token repl
where
-- validate if token matches the following chars of the string
-- returns Nothing if token is not matched
-- returns the remaining string after the token if token is matched
validateToken:: String -> String -> Maybe String
validateToken (a:as) [] = Nothing
validateToken [] list = Just list
validateToken (a:as) (x:xs)
| a == x = validateToken as xs
| otherwise = Nothing
example = replace "yourString" "token" "new"
推荐阅读
- javascript - 虽然单击三个按钮之一不能禁用其他两个 jQuery
- angular - Azure B2C + Angular + ASP.NET Core 2.2 托管在 Azure 重新身份验证超时问题
- android - 使用 Azure DevOps 部署 Android 应用并针对不同环境编辑 APK
- flask - Kubernetes NGINX 找不到 uWSGI 应用程序服务器,但使用 docker-compose
- sql-server - 脚本任务无法生成动态 Excel 工作簿
- wordpress - 自定义字段的插件?
- scrapy - 启动器中的致命错误:无法使用“c:\bld\scrapy_345323\_h_env\python.exe”创建进程
- facebook - 如何使用广告帐户 ID 从 Facebook 图形 API 检索业务经理 ID
- java - 使用流检索工资最低的员工列表
- javascript - 使用 JavaScript 事件而不是 MooTools Element.Event