开发者

Code condensing/efficiency

I'm writing a string replacing function to replace smiles with there actual image location but the code is going to be very big and messy because of all the nested ifs but i cant think of a more efficient way of writing the code.

Public Function exchangeSmilies(ByVal postString As String) As String
    Dim ChangedString = postString
    ChangedString.ToLower()
    If ChangedString.Contains(":)") Then
        ChangedString = ChangedString.Replace(":)", GetSmilieMapPath("smile.gif"))
        If ChangedString.Contains(":p") Then
            ChangedString = ChangedString.Replace(":p", GetSmilieMapPath("toungue.gif"))
            If ChangedString.Contains(";)") Then
                ChangedString = ChangedString.Replace(";)", GetSmilieMapPath("wink.gif"))
                If ChangedString.Contains("<3") Then
                    ChangedString = ChangedString.Replace("<3", GetSmilieMapPath("heart.gif"))
                End If
            End If
        End If
    End If
    Return ChangedString
End Function

Public Function GetSmilieMapPath(ByVal SmilieImage As String) As String
    GetSmilieMapPath = "<img src=" & Chr(34) & "../Images/Smilies/" & Smilie开发者_运维技巧Image & Chr(34) & ">"
    Return GetSmilieMapPath
End Function


Use a Dictionary instead.

Create a dictionary like the following at the class level:

Dim dictionary As New Dictionary(Of String, String)
dictionary.Add(":)", GetSmiliePath("smile.gif"))
dictionary.Add(":p", GetSmiliePath("tongue.gif"))
...

In the exchangeSmilies function, you can loop through this dictionary to replace any occurrences:

...
For Each pair In dictionary
    If ChangedString.Contains(pair.Key) Then
        ChangedString = ChangedString.Replace(pair.Key, pair.Value)
    End If
Next
Return ChangedString


Have a Dictionary(Of String, String) that contains each of your emoticons and replacement. Use a loop to do the actual replacement.


I haven't done vb.net for a long time so I can't give you exact code. But the basic idea is this: Make a map where it contains keys of symbols (":)") and values of filename ("smile.gif"). Make that a static member variable. Then just iterate over the map and do your if (string contains map.key) then replace map.key in string with f(map.value).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜