我有一个超过160个字符的字符串,我希望将字符串分成160个字符的部分。如何通过for循环实现这一目标?
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 :(得分: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