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