将字符串拆分为没有分隔符的数组

时间:2012-07-26 18:23:56

标签: c# .net vb.net

我有一个像s = "abcdefgh"这样的字符串。我想按照以下字符分割它:

a(0)="ab"
a(1)="cd"
a(2)="ef"
a(3)="gh"

有人可以告诉我该怎么做吗?

4 个答案:

答案 0 :(得分:2)

您可以使用正则表达式拆分为两个字符的组:

Dim parts = Regex.Matches(s, ".{2}").Cast(Of Match)().Select(Function(m) m.Value)

演示:http://ideone.com/ZVL2a(C#)

答案 1 :(得分:2)

这是一个不需要编写循环的Linq方法:

    Const splitLength As Integer = 2
    Dim a = Enumerable.Range(0, s.Length \ splitLength).
        Select(Function(i) s.Substring(i * splitLength, splitLength))

答案 2 :(得分:1)

每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

答案 3 :(得分:0)

我会使用List(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 '