2009-09-14 47 views
0

如何爲字符串創建我自己的字包裝函數?我希望每行不超過50個字符,並尊重現有的CRLF。爲字符串創建我自己的字包裝器

+0

你的意思是你想添加一個新行,如果沒有一個已經每50個字符? – RichardOD 2009-09-14 13:31:57

回答

1

這樣的事情,這將讓你開始(只是一個快速samle我一起搗碎):

Private Sub Doit()  
    Dim Source As String = "" 
    Source &= "How to make my own word wrap function for string, I want each line to be no longer than 50chars and take respect existing CRLFs" & vbCrLf & vbCrLf 
    Source &= "So this will be a new row." 
    Dim wrappedtext As String = wrap(Source, 20, vbNewLine) 
    MsgBox(wrappedtext) 
End Sub 

Function wrap(ByVal text As String, ByVal maxlength As Integer, ByVal newline As String) As String 

    Dim tmp() As String = Split(text.Replace(vbCrLf, " | "), " ") 
    Dim ret As String = "" 
    Dim wrk As String = "" 
    For Each word As String In tmp 
     If word = "|" Then 
      ret &= newline 
      wrk = "" 
     ElseIf word = "" Then 

     Else 

      If Len(wrk & word) <= maxlength Then 
       wrk &= " " & word 
      Else 
       ret &= wrk & newline 
       wrk = word & " " 
      End If 

     End If 
    Next 
    If wrk <> "" Then ret &= wrk 
    Return ret 
End Function 
+0

謝謝,不錯的代碼,但有時會留下中間的單詞!也有雙倍的時間空間。 – Tom 2009-09-14 14:10:34

+0

是的。我只是把它放在一起,所以它只是一個「原型」。但從那裏解決它不應該是一件困難的任務。 – Stefan 2009-09-14 14:26:05

0

從哪個角度來看?軟件架構?

看看裝飾模式。如果您喜歡使用流,請在「Heads First:Design Patterns」一書中提出一個字符串修飾符。它是用Java編寫的,但一般編程概念的描述很好。有些頁面丟失,但您可以找到許多信息here

該算法本身是微不足道的,不是嗎?

相關問題