.net 如何将字符串拆分为固定长度的字符串数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7376987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:53:08  来源:igfitidea点击:

How to split a string into a fixed length string array?

.netvb.netstringsplit.net-1.1

提问by Yoga Fire

I have a long string like this

我有一个像这样的长字符串

dim LongString as String = "123abc456def789ghi"

And I want to split it into a string array. Each element of the array should be in 3 characters length

我想把它拆分成一个字符串数组。数组的每个元素的长度应为 3 个字符

For example,

例如,

Dim LongArray(5) As String
LongArray(0)  = "123"
LongArray(1)  = "abc"
LongArray(2)  = "456"
LongArray(3)  = "def"
LongArray(4)  = "789"
LongArray(5)  = "ghi"

How do I split it using VB.net code?

如何使用 VB.net 代码拆分它?

采纳答案by chrissie1

This could work.

这可以工作。

 Module Module1

    Sub Main()
        Dim LongString As String = "123abc456def789ghi"
        Dim longlist As New List(Of String)
        For i As Integer = 0 To Convert.ToInt32(LongString.Length / 3) - 1
            longlist.Add(LongString.Substring(i * 3, 3))
        Next
        For Each s As String In longlist
            Console.WriteLine(s)
        Next
        Console.ReadLine()
    End Sub

End Module

And this should work in .Net 1.1

这应该适用于 .Net 1.1

Module Module1

    Sub Main()
        Dim LongString As String = "123abc456def789ghi"
        Dim longlist(Convert.ToInt32(LongString.Length / 3) - 1) As String
        For i As Integer = 0 To Convert.ToInt32(LongString.Length / 3) - 1
            longlist(i) = (LongString.Substring(i * 3, 3))
        Next
        For i As Integer = 0 To Convert.ToInt32(LongString.Length / 3) - 1
            Console.WriteLine(longlist(i))
        Next
        Console.ReadLine()
    End Sub

End Module

回答by Aaron

You could use LINQ like so:

你可以像这样使用 LINQ:


' VB.NET
Dim str = "123abc456def789ghij"
Dim len = 3
Dim arr = Enumerable.Range(0, str.Length / len).Select (Function(x) str.Substring(x * len, len)).ToArray()


// C#
var str = "123abc456def789ghij";
var len = 3;
var arr = Enumerable.Range(0, str.Length / len).Select (x => str.Substring(x * len, len)).ToArray();

Note this will only take completeoccurrences of length (i.e. 3 sets in a string 10 characters long).

请注意,这将只需要完整出现的长度(即 10 个字符长的字符串中的 3 个集合)。

回答by Jon Skeet

This C# code should work:

这个 C# 代码应该可以工作:

public static string[] SplitByLength(string text, int length)
{
    // According to your comments these checks aren't necessary, but
    // I think they're good practice...
    if (text == null)
    {
        throw new ArgumentNullException("text");
    }
    if (length <= 0)
    {
        throw new ArgumentOutOfRangeException("length");
    }
    if (text.Length % length != 0)
    {
        throw new ArgumentException
            ("Text length is not a multiple of the split length");
    }
    string[] ret = new string[text.Length / length];
    for (int i = 0; i < ret.Length; i++)
    {
        ret[i] = text.Substring(i * length, length);
    }
    return ret;
}

Reflector converts that to VB as:

反射器将其转换为 VB 为:

Public Shared Function SplitByLength(ByVal [text] As String, _
                                      ByVal length As Integer) As String()
    ' Argument validation elided
    Dim strArray As String() = New String(([text].Length \ length)  - 1) {}
    Dim i As Integer
    For i = 0 To ret.Length - 1
        strArray(i) = [text].Substring((i * length), length)
    Next i
    Return strArray
End Function

It's possible that that isn't idiomatic VB, which is why I've included the C# as well.

这可能不是惯用的 VB,这就是我也包含 C# 的原因。

回答by vangli

I'm splitting the string by 35.

我将字符串拆分为 35。

var tempstore ="12345678901234567890123456789012345";

for (int k = 0; k < tempstore.Length; k += 35) {
    PMSIMTRequest.Append(tempstore.Substring(k,
      tempstore.Length - k > 35 ? 35 : tempstore.Length - k));
    PMSIMTRequest.Append(System.Environment.NewLine);
}

messagebox.Show(PMSIMTRequest.tostring());

回答by Kan

Last array is missing:

缺少最后一个数组:

Public Function SplitByLength(ByVal text As String, _
                                  ByVal length As Integer) As String()

  ' Argument validation elided
  Dim strArray As String() = New String((text.Length \ length)  - 1) {}
  Dim i As Integer
  For i = 0 To text.Length - 1
      strArray(i) = text.Substring((i * length), length)
  Next i

  ' Get last array:
  ReDim Preserve strArray(i)
  strArray(i) = text.Substring(i * length)
  Return strArray
End Function

回答by Amir

I have added some more logic to @jon code. This will work perfectly for the string which has length less than length passed.

我在@jon 代码中添加了更多逻辑。这对于长度小于传递的长度的字符串非常有效。

 Public Shared Function SplitByLength(ByVal [text] As String, ByVal length As Integer) As String()

    Dim stringLength = text.Length
    Dim arrLength As Integer = ([text].Length \ length) - 1 + IIf(([text].Length 
                                             Mod length) > 0, 1, 0)
    Dim strArray As String() = New String(arrLength) {}

    Dim returnString As String = ""
    Dim i As Integer
    Dim remLength As Integer = 0

    For i = 0 To strArray.Length - 1
      remLength = stringLength - i * length
      If remLength < length Then
        strArray(i) = [text].Substring((i * length), remLength)
      Else
        strArray(i) = [text].Substring((i * length), length)
      End If
    Next i

       Return  strArray
END FUNCTION

回答by xanatos

Dim LongString As String = "1234567"

Dim LongArray((LongString.Length + 2) \ 3 - 1) As String

For i As Integer = 0 To LongString.Length - 1 Step 3
    LongArray(i \ 3) = IF (i + 3 < LongString.Length, LongString.Substring(i, 3), LongString.Substring(i, LongString.Length - i))           
Next

For Each s As String In LongArray
    Console.WriteLine(s)
Next

There are some interesting parts, the use of the \integer division (that is always rounded down), the fact that in VB.NET you have to tell to DIM the maximum element of the array (so the length of the array is +1) (this is funny only for C# programmers) (and it's solved by the -1 in the dim), the "+ 2" addition (I need to round UP the division by 3, so I simply add 2 to the dividend, I could have used a ternary operator and the modulus, and in the first test I did it), and the use of the ternary operator IF() in getting the substring.

有一些有趣的部分,\整数除法的使用(总是向下取整),事实上在 VB.NET 中你必须告诉 DIM 数组的最大元素(所以数组的长度是 +1) (这仅对 C# 程序员来说很有趣)(并且它由昏暗中的 -1 解决),“+ 2”加法(我需要将除法四舍五入为 3,所以我只需将 2 添加到股息中,我可以已经使用了三元运算符和模数,并且在第一个测试中我做到了),以及使用三元运算符 IF() 来获取子字符串。