這似乎工作得很好。我已經測試了它的消息長度爲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
如果您使用的是VB 2005或更高版本,請不要將「ArrayList」用於任何事情。對於固定大小的列表使用數組,對於可變大小使用「List(Of T)」。在你的情況下,你正在處理'Strings',所以使用'List(Of String)'。 – jmcilhinney
我建議使用'Do'或'While'循環而不是'For'。我還建議使用'Skip'和'Take'而不是'Substring',因爲如果你指定的長度超過了'String'的末尾,'Substring'將會失敗。如果你想堅持'Substring',那麼你需要執行一些算術運算來確定要獲取的子字符串的實際長度。 – jmcilhinney