2009-09-29 182 views
0

即時消息處理收據佈局,並嘗試將產品描述文本劃分爲2行(如果其長度超過24個字符)。從字符串中提取2個字

我的第一個解決方案是這樣的:

If Row.Description.Length >= 24 Then 
TextToPrint &= Row.Description.Substring(0, 24) & "  $100" 
TextToPrint &= Row.Description.Substring(24) & vbNewLine 
else 
TextToPrint &= Row.Description & filloutFunction(Row.Description.length) &"  $100" & vbNewLine 
end if 

,但它給出了這個結果。

A product with a long na $100 
me that doesn't fit   

我不知道如何使一個功能將描述分爲看起來像我們正常看到它。

A product with a long  $100 
name that doesn't fit 

希望我自己清楚/:

回答

0

我的第一炮,

private static List<string> SplitSentence(string sentence, int count) 
{ 
    if(sentence.Length <= count) 
    { 
     return new List<string>() 
       { 
        sentence 
       }; 
    } 

    string extract = sentence.Substring(0, sentence.Substring(0, count).LastIndexOfAny(new[] 
                         { 
                          ' ' 
                         })); 

    List<string> list = SplitSentence(sentence.Remove(0, extract.Length), count); 

    list.Insert(0, extract.Trim()); 

    return list; 
} 

等:

string sentence = "A product with a long name that doesn't fit"; 

List<string> sentences = SplitSentence(sentence, 24); 
sentences[0] = sentences[0] + "  $100"; 

我認爲這是可能的優化。

+1

謝謝!我發現這個有用的! – Alexander 2009-09-29 12:48:11

1

如果大於24則尋找從點23遞減一個空格字符。一旦找到它,將該位置上的字符串分開。那個'列'系統看起來很討厭 - 這個輸出在哪裏,屏幕?

+0

到收據打印機。 紙上的一行寬度爲42個字符。我需要重新包裝18個字符的「金額欄」有一個「右對齊」 – Alexander 2009-09-29 12:17:39

+0

啊,那麼可以理解。 – UpTheCreek 2009-09-29 13:24:19

0

像這樣的東西應該工作:

Dim yourString = "This is a pretty ugly test which should be long enough" 
Dim inserted As Boolean = False 
For pos As Integer = 24 To 0 Step -1 
    If Not inserted AndAlso yourString(pos) = " "c Then 
     yourString = yourString.Substring(0, pos + 1) & Environment.NewLine & yourString.Substring(pos + 1) 
     inserted = True 
    End If 
Next 
+0

謝謝!完美的工作! – Alexander 2009-09-29 12:32:09