将文本格式化为列

时间:2012-12-03 20:15:14

标签: vb.net string visual-studio-2010

我用VB.NET编写程序已经很久了,但现在我正在尝试编写一个WinForm应用程序。我有几个字符串,我想将它们放在一起,以便它们可以添加到ListView控件。

我有这个:

text1 = ("00 | 34123 | 232")
text2 = ("023 | 233 | 23332 ")
text2 = ("00 | 2342432 | 122 ")

但我想要这个:

text1 = ("00     |     34123       |  232   ")
text2 = ("023    |     233         |  23332 ")
text2 = ("00     |     2342432     |  122   ")

请注意,每个数字都是一个字符串变量,因此每个数字可以是:“12”或“123”或“1234”...我怎么能这样做??

2 个答案:

答案 0 :(得分:1)

您想使用String.PadRight方法。

使用示例:

Dim result = "00".PadRight(7) & "|    " _
             & "34123".PadRight(12) & "|  " _
             & "232".PadRight(6)

在这种情况下,String.Format方法甚至更好。请注意,对于这两种工作方法,您需要使用固定宽度的字体。

答案 1 :(得分:1)

Public Function ToFixedColumns(ByVal input As String) As String
    'Separate individual items 
    Dim values = input.Split("|"c).Select(Function(s) s.Trim()).ToArray()

    'Validate split operation
    If values.Length <> 3 Then 
        Throw New InvalidArgumentException("The string was not in the correct starting format.")
    End If

    'Create new formatted string
    Return String.Format("{0,-6} |     {1,-12}  |  {2,-6}", _
           values(0),values(1),values(2))
End Function
相关问题