从字符串中提取2个字

问题描述:

即时消息处理收据布局,并尝试将产品描述文本划分为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 

希望我自己清楚/:

我的第一炮,

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

如果大于24则寻找从点23递减一个空格字符。一旦找到它,将该位置上的字符串分开。那个'列'系统看起来很讨厌 - 这个输出在哪里,屏幕?

+0

到收据打印机。 纸上的一行宽度为42个字符。我需要重新包装18个字符的“金额栏”有一个“右对齐” – Alexander 2009-09-29 12:17:39

+0

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

像这样的东西应该工作:

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