Note, that our function is a wrapper based on character counting; we are not measuring the rendered text width within a given device context. By the way, "LineWrap" is another, slightly better, term for what the function does: wrapping lines at word boundaries; nevertheless, "WordWrap" is more common.|
Function WordWrap( _
ByRef Text As String, _
ByVal Width As Long, _
Optional ByRef CountLines As Long) As String
Note the following points:
- Text can be wrapped at space (ASCII 32) and hyphen (ASCII 45) characters.
- Words that are longer than Width are cut.
- We wrap lossless: no string characters of the original string are replaced, so that the output is fully revertible to the input by simply removing the line break characters. To achieve this, lines wrapped at a space character will end in that space character (see examples below). In other words, the space behaves exactly as a wrapping hyphen.
- The line break character is fixed to 2-byte vbCrLf (ASCII 13 & ASCII 10).
- No line breaks are added to the very end of the output (see last example below).
- Any line break characters in the original string are ignored. It's the responsability of the caller to take care of removing them.
- If Width is 0 the function returns an empty string.
- CountLines is an optional return argument that's handy when you need to know the height of the wrapped string returned or whether anything has been wrapped (CountLines > 1).
|Examples (the comma stands for vbCrLf):
WordWrap("ab cdef ghi", 2) --> "ab ,cd,ef ,gh,i"
WordWrap("ab cdef ghi", 3) --> "ab ,cde,f ,ghi"
WordWrap("ab cdef ghi", 4) --> "ab ,cdef ,ghi"
WordWrap("ab-cdef-ghi", 4) --> "ab-,cdef-,ghi"
WordWrap("abcedef", 0) --> ""
WordWrap("abcedef", 1) --> "a,b,c,d,e,f,g"
WordWrap("abcedef", 2) --> "ab,cd,ef,g"
WordWrap("abcedef", 3) --> "abc,def,g"
WordWrap("a ", 1) --> "a " (not "a ,")
Use this function (VB5/6-compatible) to verify the correctness of your code.