如何用x个字符分割字符串

Mar*_*mer 9 vb.net string

我有一个程序,用户以字符串的形式输入数字列表.此数字列表始终是8的倍数.

因此列表可以包含8,16,32,40,48等数字.

我需要将该字符串拆分为每8个字符.

例如,假设用户输入了"1234123445674567"

如何将其拆分为字符串数组,其中(0)为"12341234",(1)为"45674567"

注意:数组的大小必须等于字符串的长度除以8.

像这样:

Dim stringArray(txtInput.Text.Length/8) as String
Run Code Online (Sandbox Code Playgroud)

编辑:我知道我可以通过制作一个计数8个数字的循环并将其分成一个数组来实现这一点,但这将是冗长的并采取一些变量,我知道有一种更有效的方法来做到这一点.我只是不知道语法.

das*_*ght 6

这应该将字符串拆分为 8 个字符的子字符串数组

Dim orig = "12344321678900987"
Dim res = Enumerable.Range(0,orig.Length\8).[Select](Function(i) orig.Substring(i*8,8))
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,VB 足够聪明,不需要`[Select]`。 (5认同)
  • 是的,没有人想再写 VB 了 :) VB 中跟在 `.` 后面的关键字不需要用 `[]` 转义就可以了。所以你可以用`.Select` 让它更整洁一点。 (4认同)

Ry-*_*Ry- 5

您可以使用For循环和Substring

Dim strings As New List(Of String)

For i As Integer = 0 To Me.txtInput.Text.Length - 1 Step 8
    strings.Add(Me.txtInput.Text.Substring(i, 8))
Next
Run Code Online (Sandbox Code Playgroud)

要将strings列表转换为数组(如果确实需要一个数组),可以使用strings.ToArray()


另外,您可以使用正则表达式和LINQ来制作精美的单线:

Text.RegularExpressions.Regex.Matches(Me.txtInput.Text, ".{8}").Select(Function(x) x.Value)
Run Code Online (Sandbox Code Playgroud)