【问题标题】:Get the `Middle` of a string with certain prefix and postfix?获取具有特定前缀和后缀的字符串的“中间”?
【发布时间】:2014-11-11 18:19:09
【问题描述】:

以下活动模式不使用正则表达式以获得更好的性能。不过,这似乎颇有程序风格。这是用 F# 编写的更好方法吗?

let (|Middle|_|) prefix postfix (input : string) =
    if input.StartsWith(prefix) && input.EndsWith(postfix)
          && input.Length > prefix.Length + postfix.Length then
        let len = input.Length - prefix.Length - postfix.Length
        Some(input.Substring(prefix.Length, len))
    else None

【问题讨论】:

    标签: f#


    【解决方案1】:

    我觉得没问题。 为什么你认为它没有功能? 为了使用字符串切片,我只会更改最后一行:

    if input.StartsWith(prefix) && input.EndsWith(postfix)
          && input.Length > prefix.Length + postfix.Length then
        Some(input.[prefix.Length .. input.Length - postfix.Length - 1])
    else None
    

    无论如何,我不认为它使它更实用。

    【讨论】:

    • 我认为它也可能对 if 条件有更好的模式匹配方法。
    • 是的,你可以使用 match,但是如果你能用“if .. then”来解决它就好了。 If-then 在纯函数式语言中也是一个函数。
    • 也许很挑剔,但if/else 是一个表达式
    猜你喜欢
    • 1970-01-01
    • 2013-11-15
    • 2021-09-16
    • 2011-10-05
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多