2017-08-02 66 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

相關問題