Cor Ligthert said:
...
This is in my opinion not a complex string manipulation this is a very
simple array manipulation, so show an example where the stringbuilder is
faster in this sample?
Your main argument against regex's was that they're complex and slow: Using
String.Split is nice, but it's known to be slow. And Functions like StrConv
are nice too, but they are complex.
This should show the time difference:
Module Module1
Sub Main()
Dim d0 As DateTime, d1 As DateTime, d2 As DateTime
d0 = DateTime.Now
For i As Integer = 0 To 100000
Test1()
Next
d1 = DateTime.Now
For i As Integer = 0 To 100000
Test2()
Next
d2 = DateTime.Now
Console.WriteLine("Using String.Split: {0}", New TimeSpan(d1.Ticks -
d0.Ticks))
Console.WriteLine("Using StringBuilder: {0}", New
TimeSpan(d2.Ticks - d1.Ticks))
End Sub
Function Test1() As String
Dim myStr As String = "MY_STRING_TO_BE_CONVERTED"
Dim myArr() As String = myStr.Split("_"c)
For i As Integer = 0 To myArr.Length - 1
myArr(i) = StrConv(myArr(i), VbStrConv.ProperCase)
Next
Test1 = String.Join("", myArr)
End Function
Function Test2() As String
Dim myStr As String = "MY_STRING_TO_BE_CONVERTED"
Dim builder As New System.Text.StringBuilder
Dim nextCharLower As Boolean = False
For i As Integer = 0 To myStr.Length - 1
If myStr.Chars(i) = "_"c Then
nextCharLower = False
Else
If nextCharLower Then
builder.Append(Char.ToLower(myStr.Chars(i)))
Else : builder.Append(myStr.Chars(i))
End If
nextCharLower = True
End If
Next
Test2 = builder.ToString
End Function
End Module
Sorry if the code's not that pretty. VB isn't my "mother language".
Niki