Converting "," to " ", but not within a string.

robertb_NZ

Well-known member
Joined
May 11, 2010
Messages
146
Location
Auckland, New Zealand
Programming Experience
10+
I have written this routine which seems to work perfectly, but is there a better way (more efficient, more concise) ?

Function ReplaceCommas(Linein As String) As String
' Replace "," with " ", except where they are within a string
Dim SB As New StringBuilder
Dim StringState As Boolean = False
For I = 1 To Len(Linein)
Dim Char1 As String = Mid(Linein, I, 1)
If Char1 = "'" Then StringState = Not StringState
If Char1 = "," AndAlso Not StringState Then
SB.Append(" ")
Else
SB.Append(Char1)
End If
Next
Return SB.ToString
End Function
 
Hi,

The biggest issue with the code that you have posted is your use of old VB6 Functions. Here is another option for you which takes advantage of the Split and Replace Methods in .NET.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Dim someString As String = "The Questions are 'What is your name?, What is your Age',The Answers are 'Ian, 21 (again)'"
 
  MsgBox(StripCommasOutsideOfLiteral(someString))
End Sub
 
Private Function StripCommasOutsideOfLiteral(ByVal myString As String) As String
  Dim stringElementArray() As String = myString.Split("'"c)
 
  'By splitting the string by the Single Quote characters you know that only the Even Elements in the Array
  'are outside of the Literal Quotes within the string so you can call the Replace method on these elements only.
  For Counter As Integer = 0 To stringElementArray.Length - 1 Step 2
    stringElementArray(Counter) = stringElementArray(Counter).Replace(",", Space(1))
  Next
 
  'Rejoin the string with Single Quote Characters and return the result
  Return String.Join("'", stringElementArray)
End Function


If you use a Stopwatch to perform some bench mark tests you will find that the above example is about 12 times faster than what you have now.

Hope that helps.

Cheers,

Ian
 
Back
Top