2017-08-02 27 views
0

我有一个字符串超过160个字符,我希望字符串被分成160个字符的部分。我如何用for循环来实现这一点?将字符串组为160个字符并将它们添加到数组列表中

 
Dim message = "" /has 481 characters 

      If message.Length > 160 Then 
       Dim multiPartMessages As New ArrayList() 

       For i As Integer = 0 To message.Length - 1 Step 160 
        multiPartMessages.Add(message.Substring(i, 160)) 
       //should add 4 arrays, 3 of them having 160 characters each and the fourth with just one 
       Next 


      Else 
       //code runs 

      End If 
+0

如果您使用的是VB 2005或更高版本,请不要将“ArrayList”用于任何事情。对于固定大小的列表使用数组,对于可变大小使用“List(Of T)”。在你的情况下,你正在处理'Strings',所以使用'List(Of String)'。 – jmcilhinney

+1

我建议使用'Do'或'While'循环而不是'For'。我还建议使用'Skip'和'Take'而不是'Substring',因为如果你指定的长度超过了'String'的末尾,'Substring'将会失败。如果你想坚持'Substring',那么你需要执行一些算术运算来确定要获取的子字符串的实际长度。 – jmcilhinney

回答

0

这似乎工作得很好。我已经测试了它的消息长度为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 
+0

看到这里,https://stackoverflow.com/questions/8774392/how-to-split-a-string-by-x-amount-of-characters,这可能有帮助。一个内衬的一些很好的例子来做到这一点。 – SQLAndOtherStuffGuy

相关问题