【问题标题】:Group string by 160 characters and add them into an arraylist将字符串按 160 个字符分组并将它们添加到数组列表中
【发布时间】:2018-01-09 05:24:58
【问题描述】:

我有一个超过 160 个字符的字符串,我希望将字符串分成 160 个字符的部分。如何使用 for 循环实现这一点?

暗消息 = "" /有 481 个字符 如果 message.Length > 160 那么 将 multiPartMessages 调暗为新的 ArrayList() For i As Integer = 0 To message.Length - 1 Step 160 multiPartMessages.Add(message.Substring(i, 160)) //应该添加 4 个数组,其中 3 个每个有 160 个字符,第四个只有一个 下一个 别的 //代码运行 万一

【问题讨论】:

  • 如果您使用的是 VB 2005 或更高版本,请永远不要使用 ArrayList。对固定大小的列表使用数组,对可变大小的列表使用List(Of T)。在你的情况下,你正在处理Strings,所以使用List(Of String)。
  • 我建议使用Do 或While 循环而不是For。我还建议使用Skip 和Take 而不是Substring,因为如果您指定的长度超出String 的末尾,Substring 将失败。如果您想坚持使用Substring,那么您需要执行一些算术来确定要获取的子字符串的实际长度。

标签: vb.net for-loop arraylist


【解决方案1】:

这似乎运作良好。我已经用 0,3,160,320,323 个字符的消息长度对其进行了测试。有一些更短的写法,但为了(一些)清楚起见,我发布了这个。

Private Sub SendMessage(message As String)
    If message.Length > 0 Then
        Dim multiPartMessages As New List(Of String)
        'get the number of parts that are 160 characters in length
        Dim fullParts As Integer = CInt(message.Length / 160)
        'calculate the remaining number of characters
        Dim lastPartLength = message.Length - (fullParts * 160)
        'if the full message>160 characters in length loop through the string
        'in steps of i*160 and add each substring to multiPartMessages
        Dim i As Integer
        While i < fullParts And fullParts > 0
            multiPartMessages.Add(message.Substring(i * 160, 160))
            i += 1
        End While
        'if the last part has more than 0 characters then add them all to multiPartMessages
        If lastPartLength > 0 Then
            multiPartMessages.Add(message.Substring(fullParts * 160, lastPartLength))
        End If
    Else
        'handle 0 length message here
    End If
End Sub

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多