我在 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.Split
的 Ruben's 建议:let stripv3 (stripChars:string) (text:string) =
text.Split(stripChars.ToCharArray(), StringSplitOptions.RemoveEmptyEntries) |> String.Concat
关于string - 从 f# 中的字符串中删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20308875/