You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell递归处理字符串后在开头添加字符的实现方法求教

Haskell字符串处理解决方案

你需要的功能可以拆分成两个部分:递归替换指定字符,以及在结果前添加前缀。以下是实现代码:

字符替换函数(递归实现)

首先写一个递归函数处理每个字符的替换逻辑:

replaceChars :: String -> String
replaceChars [] = []  -- 递归终止条件:空字符串返回空
replaceChars (c:cs) = case c of
    ' ' -> '_' : replaceChars cs  -- 空格替换为下划线,继续处理剩余字符
    'd' -> 'g' : replaceChars cs  -- 'd'替换为'g',继续处理剩余字符
    _   -> c : replaceChars cs    -- 其他字符保持不变,继续处理剩余字符

主函数(添加前缀)

再写一个主函数,调用上面的替换函数后,在结果开头加上'/':

formatString :: String -> String
formatString s = '/' : replaceChars s

测试示例

输入"Hello world"时:

  1. replaceChars "Hello world"会返回"Hello_worlg"
  2. formatString "Hello world"最终返回"/Hello_worlg",完全符合你的需求。

如果想把逻辑合并到单个函数里,也可以这样写:

formatString :: String -> String
formatString [] = "/"  -- 空输入返回"/"
formatString s = '/' : go s
    where
        go [] = []
        go (x:xs) = case x of
            ' ' -> '_' : go xs
            'd' -> 'g' : go xs
            _   -> x : go xs

内容的提问来源于stack exchange,提问作者Nunya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:00:59