1

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/" & SmilieImage & Chr(34) & ">" Return GetSmilieMapPath End Function 
3
  • 1
    Your code as written doesn't do what you want. If a string contains <3 but not :, your code won't do any replacements. Start by un-nesting all these if's. Then if it still looks messy, try the dictionary approach other answers suggest. Commented Jun 2, 2011 at 14:25
  • You don't need to do String.Contains before calling String.Replace. Commented Jun 2, 2011 at 14:29
  • +1, I also need similar solution Commented Jun 2, 2011 at 20:43

3 Answers 3

4

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 
Sign up to request clarification or add additional context in comments.

1 Comment

String.Contains can be omitted - if pair.Key isn't in there, String.Replace will return the original string.
3

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

Comments

0

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.