Suggerimenti per migliorare l'accorciatore di URL VB.NET?
Domanda
Ecco la mia funzione ( aggiornata ):
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
Ho risolto il problema in cui non restituiva i caratteri maxLength
perché non teneva conto delle ellissi.
Mi sembra troppo complicato; eventuali suggerimenti, commenti, dubbi sono più che benvenuti.
Soluzione
Perché non farlo?
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
Questo almeno elimina tutte le dichiarazioni temporanee
Altri suggerimenti
Beh, non so se sia troppo complicato ... ma è sbagliato. Se chiamo shortenUrl (URL, 29), mi aspetto che il ritorno abbia una lunghezza massima di 29 caratteri. Il tuo codice mi darebbe 31. Se lo chiamo con una lunghezza di 30, riceverò 33 caratteri. Non stai includendo il " ... " ;, inserito e stai facendo affidamento sull'arrotondamento per ottenere le lunghezze della sottostringa e far cadere il resto.
Aggiungo un po 'di validazione param e la cambio in:
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
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
Non so perché le persone odiano così tanto gli argomenti opzionali. Fanno esattamente la stessa cosa e espongono all'utente quale valore verrà predefinito se non ne forniscono uno.