0

I have a string that's more than 160 characters and I want the string to be divided into parts of 160 characters. How can I achieve this with a for loop?

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
Keith Yung
  • 113
  • 1
  • 10
  • If you're using VB 2005 or later, don't use an `ArrayList` for anything, ever. Use an array for fixed-size lists and a `List(Of T)` for variable-size. In your case, you're dealing with `Strings` so use a `List(Of String)`. – jmcilhinney Aug 02 '17 at 06:46
  • 1
    I would suggest using a `Do` or `While` loop rather than `For`. I would also suggest using `Skip` and `Take` rather than `Substring`, because `Substring` will fail if you specify a length that goes beyond the end of the `String`. If you want to stick with `Substring` then you'll need to perform some arithmetic to determine the actual length of the substring to get. – jmcilhinney Aug 02 '17 at 06:53

1 Answers1

0

This seems to work well. I've tested it with a message length of 0,3,160,320,323 characters. There are shorter ways of writing this, but I posted this for (some) clarity.

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
David Wilson
  • 4,369
  • 3
  • 18
  • 31
  • See here, https://stackoverflow.com/questions/8774392/how-to-split-a-string-by-x-amount-of-characters, this might help. Some good examples of one liners to do this. – SQLAndOtherStuffGuy Aug 03 '17 at 07:23