CONCLUSION: I used a regular expression, which handles both numbers and letters in strings of arbitrary length, in one line of code.
dim rtn as String = Regex.Replace(input, "..", "$& ")
I'd like to take numeric strings of arbitrary length and insert a space every 2 characters. So 1233456 becomes 12 33 45 6.
Is there a way I can use format as string or IFormatProvider, like? That would put a limit on how long the string could be though, right? Since I'm casting to a long.
CLng((input)).ToString("## ")
EDIT - here's the original question. I'd like to take strings of arbitrary length and insert a space every 2 characters. 123dssas4rr should become 12 3d ss as 4r r
I was clumsily using
Dim rtn As String = String.Empty
Dim i As Integer = 0
For Each a In input.ToCharArray
rtn = String.Concat(rtn, a)
i = i + 1
If i Mod 2 = 0 Then
rtn = String.Concat(rtn, " ")
End If
Next
You could do something as simple as this
Maybe not the prettiest but a simple and fast approach is the plain old StringBuilder:
Edit:
Compared the StringBuilder with the Regex approach just for interest:
Result:
StringBuilder is 12 times faster on 10 millionen iterations even though it creates a new StringBuilder object on every iteration. The difference will be the greater, the longer the string is. Sometimes shorter solutions are not faster, same would apply to a LINQ approach.
Even if this test was not really practically relevant, if i change it to read a string from a file with 500.000 chars(500kb)and iterate 100 times, the result is even better for StringBuilder:
StringBuilder approach is nearly 20 times faster.
Here is an extension version:
You can call it in following way:
or in VB
You'll need to import
System.Text.RegularExpressions
(or add the namespace name beforeRegex
.If you're willing to
Trim
the string after replacing, then you can get rid of the parentheses (and the stuff inside them) entirely. You need one or the other, though, so that a string with an even number of chars doesn't have an extra space at the end.I'll give you the algorithm and you code, ok?
Voila!