1

这是我的功能(更新):

Public Shared Function shortenUrl(ByVal URL As String) As String
    Return shortenUrl(URL, 32)
End Function
Public Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String
    If URL.Length > maxLength Then
        String.Format("{0}...{1}", URL.Substring(0, (maxLength / 2)), URL.Substring(URL.Length - ((maxLength / 2) - 3)))
    Else
        Return URL
    End If
End Function

我修复了它没有返回maxLength字符的问题,因为它没有考虑到省略号。


在我看来,这太复杂了;任何建议、评论和关注都非常受欢迎。

4

3 回答 3

1

为什么不这样做?

Public Shared Function shortenUrl(ByVal URL As String) As String
    Return shortenUrl(URL, 29)
End Function
Public Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String
    If URL.Length > maxLength Then
        Return String.Format("{0}...{1}", URL.Substring(0, maxLength / 2),URL.Substring(URL.Length - (maxLength / 2)))
    Else
        Return URL
    End If
End Function

这至少摆脱了所有的临时声明

于 2008-10-22T20:35:11.760 回答
1

好吧,我不知道它是否太复杂了......但它是错误的。如果我调用 shortUrl(URL, 29) 我希望返回的最大长度为 29 个字符。你的代码会给我 31。如果我用 30 的长度调用它,我会得到 33 个字符。您不包括插入的“...”,而是依靠舍入来获取子字符串长度并删除其余部分。

我会添加一些参数验证,并将其更改为:

Public Function shortenUrl2(ByVal URL As String, ByVal maxLength As Integer) As String
    Const middle as String = "..."
    If maxLength < 0 Then
       Throw New ArgumentOutOfRangeException("maxLength", "must be greater than or equal to 0")
    ElseIf String.IsNullOrEmpty(URL) OrElse URL.Length <= maxLength Then
       Return URL
    ElseIf maxLength < middle.Length Then
       Return URL.Substring(0, maxLength)
    End If

    Dim left as String = URL.Substring(0, CType(Math.Floor(maxLength / 2), Integer))
    Dim right as String = URL.Substring(URL.Length - (maxLength - left.Length - middle.Length))

    Return left & middle & right
End Function
于 2008-10-22T21:51:20.703 回答
0
Public Shared Function shortenUrl(ByVal URL As String, Optional ByVal maxLength As Integer = 29) As String
    If URL.Length > maxLength Then       
        Return String.Format("{0}...{1}", URL.Substring(0, maxLength / 2), URL.Substring(URL.Length - (maxLength / 2)))
    Else
        Return URL
    End If
End Function

不知道为什么人们如此讨厌可选参数。他们做完全相同的事情并向用户公开如果他们不提供默认值将是什么值。

于 2008-10-22T20:37:17.090 回答