VBcoders Guest



Don't have an account yet? Register
 


Forgot Password?



Split String for Word Wrapping

by Gajendra S. Dhir (3 Submissions)
Category: Miscellaneous
Compatability: Visual Basic 3.0
Difficulty: Intermediate
Date Added: Wed 3rd February 2021
Rating: (6 Votes)

Breaks up a string so that it can be effectively printed - word wrapped - using the Print statement.


SplitLines is a function in Visual Basic to return an array of strings from a long string such that the each array element has its P.TextWidth(Lines(i)) < W. The function uses the current font settings of the object P which could be a Form, a PictureBox or the Printer object.

Inputs

Txt     -> is the String that is to be split
P      -> a Form, a PictureBox or the Printer object. The font settings
        of this will be used to determine the TextWidth
W      -> the maximum width of the string array

Assumes
Example Usage =============
  Dim Ltxt() as string
  Dim OriStr as string
  OriStr = "This contains the string that is to be split...... ..."
  Ltxt = SplitLines(OriStr, Form1, 1500)
  For i = 1 to UBound(Ltxt)
    Form1.Print Ltxt(i)
  Next i

Code Returns
An array of strings.
Side Effects
The function counts on the fact that font characteristics for the object P has been set.
Rate Split String for Word Wrapping

Public Function SplitLines(Txt As String, P As Object, W As Single) As String()
Dim Lines() As String, CurrW As Single, CurrWord As String
Dim L As Integer, i As Integer, WCnt As Integer
CurrW = 0
L = Len(Txt)
If (P.TextWidth(Txt) > W) Or (InStr(Txt, vbCr) > 0) Then
i = 1
WCnt = 1
ReDim Lines(WCnt) As String
Do Until i > L
CurrWord = ""
Do Until i > L Or Mid(Txt, i, 1) <= " "
CurrWord = CurrWord & Mid(Txt, i, 1)
i = i + 1
Loop
If CurrW + P.TextWidth(CurrWord) > W Then
WCnt = WCnt + 1
ReDim Preserve Lines(WCnt) As String
CurrW = 0
End If
Lines(WCnt) = Lines(WCnt) + CurrWord
CurrW = P.TextWidth(Lines(WCnt))
Do Until i > L Or Mid(Txt, i, 1) > " "
Select Case Mid(Txt, i, 1)
Case " "
Lines(WCnt) = Lines(WCnt) + " "
CurrW = P.TextWidth(Lines(WCnt))
Case vbLf
Case vbCr
WCnt = WCnt + 1
ReDim Preserve Lines(WCnt) As String
CurrW = 0
Case Chr(9)
Lines(WCnt) = Lines(WCnt) + " "
CurrW = P.TextWidth(Lines(WCnt))
End Select
i = i + 1
Loop
Loop
Else
ReDim Lines(1) As String
Lines(1) = Txt
End If
For i = 1 To WCnt
  Lines(i) = LTrim(RTrim(Lines(i)))
Next i
SplitLines = Lines
End Function

Download this snippet    Add to My Saved Code

Split String for Word Wrapping Comments

No comments have been posted about Split String for Word Wrapping. Why not be the first to post a comment about Split String for Word Wrapping.

Post your comment

Subject:
Message:
0/1000 characters