我有一个像s = "abcdefgh"
. 我想按字符数拆分它,例如:
a(0)="ab"
a(1)="cd"
a(2)="ef"
a(3)="gh"
有人可以告诉我该怎么做吗?
您可以使用正则表达式拆分为两个字符组:
Dim parts = Regex.Matches(s, ".{2}").Cast(Of Match)().Select(Function(m) m.Value)
演示: http: //ideone.com/ZVL2a (C#)
这是一个不需要编写循环的 Linq 方法:
Const splitLength As Integer = 2
Dim a = Enumerable.Range(0, s.Length \ splitLength).
Select(Function(i) s.Substring(i * splitLength, splitLength))
每 2 个字符拆分一次,这就是我认为你想要的
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
我会使用 aList(Of String)
代替,它简化了它:
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 '