|
-
Mar 8th, 2010, 06:53 AM
#1
Thread Starter
New Member
Better way of replacing?
Hi,
I have a code snippet that cleans a string of various characters.
Code:
Public Function cleanthis(ByRef stringer As String) As String
Dim stringtest As String = stringer.Trim
stringtest = stringtest.Replace("/", " ")
stringtest = stringtest.Replace(":", " ")
stringtest = stringtest.Replace(";", " ")
stringtest = stringtest.Replace("'", "")
stringtest = stringtest.Replace("(", "")
stringtest = stringtest.Replace(")", "")
stringtest = stringtest.Replace(" ", "-")
stringtest = stringtest.Replace("---", "-")
stringtest = stringtest.Replace("--", "-")
stringtest = stringtest.Replace("&", "and")
stringtest = stringtest.Replace(",", "")
cleanthis= stringtest.Trim
End Function
Is there a better way to do it than this?
Thanks for any help you can give.
Regards
Peter
-
Mar 8th, 2010, 10:04 AM
#2
Re: Better way of replacing?
Seems like this would be best to use string builder rather than keep assigning the string value on each replace.
Code:
Dim DirtyString As String = "//This is a : test;it's (should) replace items --- & also, be fast"
DirtyString.Cleaner()
Console.WriteLine(DirtyString)
Code:
<Runtime.CompilerServices.Extension()> _
Public Sub Cleaner(ByRef sender As String)
Dim SearchItems(,) As String = _
{ _
{"/", " "}, _
{":", " "}, _
{"'", ""}, _
{"---", "-"}, _
{"&", "And"}, _
{"(", ""}, _
{")", ""} _
}
Dim sb As New System.Text.StringBuilder(sender)
Dim Rows As Integer = SearchItems.GetLength(0) - 1
For Row As Integer = 0 To Rows
sb.Replace(SearchItems(Row, 0), SearchItems(Row, 1))
Next
sender = sb.ToString
End Sub
-
Mar 8th, 2010, 08:52 PM
#3
Banned
Re: Better way of replacing?
Why not use Regex??
--------------------
Sabrina Gage
Free Live Chat Software
-
Mar 9th, 2010, 09:42 AM
#4
Re: Better way of replacing?
 Originally Posted by Sabrina Gage
Why not use Regex??
--------------------
Sabrina Gage
Free Live Chat Software
To be honest I believe there is no gain in using regular expressions here.
Code:
Dim DirtyString As String = "//This is a : test;it's (should) replace items --- & also, be fast"
Dim dict As New Dictionary(Of String, String)
dict.Add("/", "")
dict.Add(":", "")
dict.Add("&", "And")
Console.WriteLine(DirtyString.DictReplace(dict))
Code:
<System.Runtime.CompilerServices.Extension()> _
Public Function DictReplace( _
ByVal sender As String, _
ByVal UserDictionary As Dictionary(Of String, String)) As String
Return Regex.Replace(sender, "(" & _
String.Join("|", UserDictionary.Keys.ToArray()) & ")", _
Function(m As Match) UserDictionary(m.Value))
End Function
Hopefully someone can poke holes at this method simply because there are issues with using a dictionary.
Last edited by kareninstructor; Mar 9th, 2010 at 10:12 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|