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

如何删除字符串末尾的指定感叹号字符,对应实现方法咨询

实现方案与问题解答

关于last函数的使用

你可以在当前边界处理的前提下使用last函数:由于你已经通过remove [] = []提前处理了空字符串场景,非空分支下调用last不会触发空输入异常。但如果没有前置的非空校验,不建议直接使用last,会有运行时报错风险。

两种主流实现方式

1. 卫兵(|)实现(更推荐)

这个场景非常适合用卫兵实现,语法简洁,符合Haskell编码惯用法:

remove :: String -> String
remove [] = []
remove s
    | last s == '!' = init s
    | otherwise = s

注:init函数用于获取除最后一位外的剩余字符串,此处非空场景下调用同样安全

如果你不想依赖last和init,也可以用反向模式匹配实现,逻辑更安全,普通场景下性能差异可以忽略:

remove :: String -> String
remove = reverse . go . reverse
    where go [] = []
          go ('!':rest) = rest
          go s = s

2. if-then分支实现

if-then写法逻辑直白,适合偏好顺序判断的场景:

remove :: String -> String
remove [] = []
remove s = if last s == '!' then init s else s

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:48:01