从字符串中提取2个单词

时间:2009-09-29 12:08:55

标签: vb.net substring

我正在使用收据布局,并尝试将产品说明文字分成2行,如果它超过24个字符。

我的第一个解决方案是这样的:

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   

希望我明确表示/:

3 个答案:

答案 0 :(得分:1)

如果大于24,则从第23点开始逐渐查找空格字符。找到后,将该字符串拆分到该位置。你所拥有的那个“专栏”系统看起来非常讨厌 - 这个输出在哪里,屏幕?

答案 1 :(得分: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

答案 2 :(得分: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";

我认为可以进行优化。