我確信有一百萬種不同的方式來做到這一點。
你基本上需要把你的所有單詞按空格分成一個列表。之後,您只需要檢查當前單詞加上空格加上下一個單詞是否達到閾值,如果是,則移至下一行。一旦你有所有的線路,然後你重新加入單一字符串列表再次。
Private Function LimitWidth(ByVal text As String, ByVal maxCharacters As Integer) As String
Dim words As List(Of String) = text.Split(" "c).ToList()
If text.Length < maxCharacters OrElse words.Count = 1 Then
Return text
Else
Dim lines As New List(Of String)
Dim currentLine As String = words(0)
For i As Integer = 1 To words.Count - 1
If (currentLine & " " & words(i)).Length > maxCharacters Then
lines.Add(currentLine)
currentLine = words(i)
If i = words.Count - 1 Then
lines.Add(currentLine)
End If
Else
If i = words.Count - 1 Then
lines.Add(currentLine & " " & words(i))
End If
currentLine &= " " & words(i)
End If
Next
Return String.Join(Environment.NewLine, lines.ToArray())
End If
End Function
測試:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
MessageBox.Show(LimitWidth("This is a really long sentence " & _
"meant to demonstrate how to split " & _
"the words into a confined character length.", 26))
End Sub
這裏是AC#回答類似的問題:http://stackoverflow.com/questions/2815021/split-large-text-string-into-variable-長度字符串沒有破碎字 它的值得注意的是,雖然大多數字體是可變寬度,所以字符數可能並不實際上對應的像素寬度 –
感謝您的答覆..我在這部分氣的應用程序...我只會縮小字體,直到他們適合..我對c一無所知,當它轉換它的充滿錯誤,我不真正下站..再次感謝.. – Skindeep2366