Search Tools Links Login

Split String for Word Wrapping


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.

Original Author: Gajendra S. Dhir

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

Assumptions

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

Returns

An array of strings.

Side Effects

The function counts on the fact that font characteristics for the object P has been set.

Code

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

About this post

Posted: 2002-06-01
By: ArchiveBot
Viewed: 91 times

Categories

Visual Basic 6

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.