从f#中的字符串中删除字符

 手机用户2502881923 发布于 2023-02-13 16:31

我有一个Liststripchars.这些字符不应出现在字符串中text.所以我把它变成了可变的.

所以我做了类似的事情:

stripchars |> Seq.iter(
    fun x ->
        text <- text.Replace(x, ' ')
    )

然后我得到一个错误,说文本是一个以无效方式使用的可变变量.现在我去看看这篇文章,我想出了类似的东西

let s = ref text    
stripchars |> Seq.iter(
    fun ch ->
        printfn "ch: %c" ch
        printfn "resultant: %s" !s
        s :=  (!s).Replace(ch, ' ')
    )

这仍然没有完成变异的状态text.什么是正确的方法?

1 个回答
  • 由于F#属于.NET堆栈,我们可能依赖于平台库的强大功能. 然后这个字符剥离任务可以实现简单

    open System
    open System.Linq
    let stripChars chars (text:string) = String.Concat(text.Except(stripChars))

    更新:不幸的是,后来我意识到Enumerable.Except方法产生了两个序列的集合差异,这意味着stripChars "a" "ababab"它只是"b"预期的而不是预期的"bbb".

    在LINQ场所继续,正确工作的实现可能更加冗长:

    let stripv1 (stripChars: seq<char>) (text:string) =
        text.Where(fun (c: char) -> not(stripChars.Contains(c))) |> String.Concat    
    

    与等效的惯用语F#相比,这可能不值得付出努力:

    let stripv2 (stripChars: seq<char>) text =
        text |> Seq.filter(fun c -> not (stripChars.Contains c)) |> String.Concat
    

    因此,纯粹的.NET特定方法将遵循Ruben关于String.Split以下评论的建议:

    let stripv3 (stripChars:string) (text:string) =
        text.Split(stripChars.ToCharArray(), StringSplitOptions.RemoveEmptyEntries) |> String.Concat
    

    2023-02-13 16:32 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有