Click here to Skip to main content
15,916,702 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I have this scenario which I declare a sentence into string. what I need to do if the first line reach the limit it will write in the next line. But my problem what if the end part of the length is a word this should be write in the next line neglecting the max length.

Here is the example

dim str as string = This is an example of my work.

--my first line should write only max of 12
obj.writeline(len(str,12) & vbNewLine) output----> This is an ex
obj.writeline(str.substring(12))output --------> ample of my work.

But What I want is to be like this.

This is an
example of my work.

Your help much appreciated.
Posted

1 solution

Hi, to achieve the result you want you need to work back from the maximum position for the first line to find the first space character, which would then be the end of the first line and the remainder of the string will become the second line.

Dim str As String = "This is an example of my work."
Dim splitPos As Integer = 12
While (str(splitPos) <> " ")
    splitPos = splitPos - 1
End While
Dim line1 As String = str.Substring(0, splitPos).Trim()
Dim line2 As String = str.Substring(splitPos).Trim()
Console.WriteLine(line1)
Console.WriteLine(line2)


Output:
This is an
example of my work.


Note: This code doesn't handle issues if the string is less than 12 characters or if there are no spaces found in the first 12 characters.

Another method you could use if you are writing a long sentence and want it split into multiple lines would be split the sentence into words and then build up a line until you reach the line limit and the output that line, then continue building the next line.

Dim str As String = "This is an example of my work."
Dim words As String() = str.Split(New Char() {" "})
Dim line As String = ""
Dim maxLen As Integer = 12
For Each word In words
    ' Is the length of the current line plus a space character and the next work too long for this line?
    If (line.Length + 1 + word.Length > maxLen) Then
        ' Yes, write out the current line, and reset
        Console.WriteLine(line)
        line = ""
    End If
    ' If this is not the first word add a space character between words
    If line.Length > 0 Then
        line = line + " "
    End If
    line = line + word
Next
Console.WriteLine(line)


Output:
This is an
example of
my work.


Note: If you want to vary the length of each line you can change the maxLen variable after writing each line, but you will need to add a line counter.

Hope this helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900