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

标签 string replace f#

我在 List<char> 中有一个 stripchars 。这些字符不应出现在字符串 text 中。所以我把它变成了可变的。

所以我做这样的事情:

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

然后我收到一条错误消息,说 text 是一个以无效方式使用的可变变量。现在我去看看 this 帖子,我得出了类似的东西
let s = ref text    
stripchars |> Seq.iter(
    fun ch ->
        printfn "ch: %c" ch
        printfn "resultant: %s" !s
        s :=  (!s).Replace(ch, ' ')
    )

这仍然无法改变 text 的状态。什么是正确的方法?

最佳答案

由于 F# 属于 .NET 堆栈,我们可以依赖平台库的强大功能。那么这个字符剥离任务就可以很简单的实现了
open System
open System.Linq
let stripChars chars (text:string) = String.Concat(text.Except(stripChars))

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

继续在 LINQ field 中,正确工作的实现可能会更加冗长:

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 特定方法是遵循以下评论中关于 String.SplitRuben's 建议:
let stripv3 (stripChars:string) (text:string) =
    text.Split(stripChars.ToCharArray(), StringSplitOptions.RemoveEmptyEntries) |> String.Concat

关于string - 从 f# 中的字符串中删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20308875/

相关文章:

Java 1.7 仍然告诉我 switch 语句中的字符串不兼容

javascript - 当函数作为第二个参数提供时,JavaScript 中的替换函数不一致

xml - 当文件具有 xmlns 属性时在 F# 中解析 xml

f# - 将一段异步 C# 代码转换为 F#(使用响应式扩展和 FSharpx)

c++ - C++ 中子字符串方法的问题

c++ - 如果 Qt 不是十六进制,则 Qt 从 QLineEdit 中删除字符

objective-c - 替换 objective-c 中的转义字符序列

javascript替换没有类的p标签的div标签

java - 从字符串中删除特定单词

f# - F# 中的自定义 IEnumerator