I have a string like s = "abcdefgh". I want to split it by number of characters like:
a(0)="ab"
a(1)="cd"
a(2)="ef"
a(3)="gh"
Can someone tell me how to do this?
I have a string like s = "abcdefgh". I want to split it by number of characters like:
a(0)="ab"
a(1)="cd"
a(2)="ef"
a(3)="gh"
Can someone tell me how to do this?
You can use a regular expression to split into two-character groups:
Dim parts = Regex.Matches(s, ".{2}").Cast(Of Match)().Select(Function(m) m.Value)
Demo: http://ideone.com/ZVL2a (C#)
[…] around the Select is unnecessary. Otherwise, this is how I’d do it as well. Just pay attention that . doesn’t match every character unless you specify the SingleLine flag.System.Linq not being a valid library: ideone.com/KlCAu. Did I do something wrong?part as var is wrong, it should just be For Each part, or alternatively … part As Match (and then the Cast would be unnecessary). But that won’t fix the internal compiler error.Here's a Linq method that doesn't require writing a loop:
Const splitLength As Integer = 2
Dim a = Enumerable.Range(0, s.Length \ splitLength).
Select(Function(i) s.Substring(i * splitLength, splitLength))
Splitting every 2 chars, is what I think you wanted
Dim s As String = "aabbccdd"
For i As Integer = 0 To s.Length - 1 Step 1
If i Mod 2 = 0 Then
Console.WriteLine(s.Substring(i, 2))
End If
Next
I you would use a List(Of String) instead, it simplifies it:
Dim s = "aabbccdde" ' yes, it works also with an odd number of chars '
Dim len = 2
Dim list = New List(Of String)
For i = 0 To s.Length - 1 Step len
Dim part = If(i + len > s.Length, s.Substring(i), s.Substring(i, len))
list.Add(part)
Next
Dim result = list.ToArray() ' if you really need that array '