Convert long line of text to multiple lines

Harris

Expert
Licensed User
Longtime User
Example: Long Line of text
Anyone have example code to accomplish this?


This is one very long line of text that needs to be broken up into several lines for proper placement on a report.


Need a list back where each line is (max) 30 characters long (keeping words together)

Example return:
This is one very long line of text
that needs to be broken up into
several lines for proper placement
on a report.

Thanks so much....
 

nfordbscndrd

Well-Known Member
Licensed User
Longtime User

B4X:
Sub Activity_Create(FirstTime As Boolean)
Dim t(100), Txt As String
Dim i, n As Int
Txt = "This is one very long line now is the time for all good men to come to the aid of their country. The quick brown fox jumped over the lazy dog."
n = 0
Do While Txt.Length > 29
   i = 29
   Do While Txt.CharAt(i) <> " " AND i > 0
      i = i - 1
   Loop
   If i > 0 Then
      t(n) = Txt.SubString2(0, i)
      n = n + 1
      Txt = Txt.SubString(i + 1)
   End If
Loop
If Txt <> "" Then t(n) = Txt
End Sub
 
Upvote 0

Harris

Expert
Licensed User
Longtime User
Thanks my friend, that's exactly what I was looking for.

I replace the hard coded width of 29 with whatever the report with needs and any long string can be spread over many lines - keeping sentences under the max width of the line. BEA utiful...
 
Upvote 0

nfordbscndrd

Well-Known Member
Licensed User
Longtime User

I just noticed a bug in the code:

If Txt has no spaces in the first 29 characters (or only at character position 0), i will go to 0 and the code after "If i > 0 Then" will not execute and the loop will repeat endlessly. Although you may not ever expect this to happen, technically the code should account for the possibility in some way, such as:

B4X:
If i = 0 Then i = 29

t(n) = Txt.SubString2(0, i)
n = n + 1
Txt = Txt.SubString(i + 1)
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…