by jeremyxtz (4 Submissions)
Category: String Manipulation
Difficulty: Beginner
Date Added: Wed 3rd February 2021
Rating: (3 Votes)
Due to the astonishing popularity of someone else's recent submission and me feeling bored...
'note if a word is longer than maxchars the word won't be split
Private Sub Form_Load()
MsgBox WrappedString("fish goes to market in the happy place and stays away in time so it does", 17)
MsgBox WrappedString("fish goes to market in the happy place and stays away in time so it does", 17)
End Sub
Function WrappedString(st As String, maxchars As Integer) As String
Dim c As Integer, i As Integer, lastc As Integer, lastspace As Integer
For i = 1 To Len(st)
c = c + 1
If Mid(st, i, 1) = " " Then lastspace = i: lastc = c
If c > maxchars And lastc <> 0 Then Mid(st, lastspace, 1) = Chr(10): c = maxchars - lastc + 1
Next
WrappedString = Replace(st, Chr(10), vbCrLf)
End Function
'same function but using a byte array. One more line but its the
'efficient way to handle strings
Function WrappedStringB(st As String, maxchars As Integer) As String
Dim stb() As Byte, c As Integer, i As Integer, lastspace As Integer, lastc As Integer
stb = st
For i = 0 To UBound(stb) Step 2
c = c + 1
If (stb(i)) = 32 Then lastspace = i: lastc = c
If c > maxchars And lastc <> 0 Then stb(lastspace) = 10: c = maxchars - lastc + 1
Next
WrappedStringB = Replace(stb, Chr(10), vbCrLf)
End Function