简体   繁体   English

Haskell用字符串替换字符串中的字符

[英]Haskell Replace characters in string with string

This is an extension of this question: Haskell replace characters in string 这是此问题的扩展: Haskell替换字符串中的字符

I would like to tweak the following expression to replace a char with a string 我想调整以下表达式以将char替换为字符串

let replaceO = map (\c -> if c=='O' then 'X'; else c)

In the end, I would the following results (XX can be a string of any length): 最后,我将得出以下结果(XX可以是任何长度的字符串):

replaceO "HELLO WORLD"
"HELLXX WXXRLD"

您可以使用concatMap

let replace0 = concatMap (\c -> if c=='O' then "X" else "XX")

You kind formulate your problem in terms of traversing and accumulating based on a condition, something like this, 您可以根据类似条件的遍历和累加来表达问题,

replace :: String -> Char -> String -> String
replace xs c s = foldr go [] xs

 where go x acc = if x == c  then acc ++ s
                             else acc ++ [x]

For you example: 以您为例:

>replace "HELLO WORLD" 'O' "XXX" 
> "HELLXXX WXXXRLD"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM