-1

我的 VB.net 上有来自存储过程的字符串变量,将其放在变量上后,我想让值具有指定的空间。

规则是这样的

在此处输入图像描述

图像上的数字平均空间,

我已经做了一些这样的试验和错误:

                Dim words As String() = receiptText.Split(" ")
                Dim word As String
                Dim XMLBuild As New StringBuilder
                XMLBuild.Append(Space(9))
                For Each word In words

                    XMLBuild.Append(word)
                    XMLBuild.Append(Space(9))

                Next

但结果是

{         PLEASE         KEEP         THIS         RECEIPT         AS         VALID         PROOF         OF         PAYMENT         }

不喜欢我应该做的规则。有没有我要使用的字符串函数?

4

3 回答 3

1

您将输入字符串拆分为每个空格,我不确定这是一个好方法,因为人名、城市地址和其他字段在单词之间有空格,但是如果您想在固定空间区域中格式化您的输入,那么我会给你一个通用的方法,至少对于你上面例子的第一行

' This is how the first line appears in the string array after the space splitting'
Dim parts = new string() {"BL", "TH", ":", "NO",  "REF.", ":", "1234567890", "R.WAHYUDIYOINO,IR"}

' This array contains the spaces reserved for each word in the string array above'
Dim spaces = new integer () {3,9,2,17,10,2,17,2,28 }

' Now loop on the strings and format them as indicated by the spaces'
' Attention, the value for space include the string itself'
Dim sb = new StringBuilder()
Dim x As INteger = 0
For each s in parts
    sb.Append(s.PadRight(spaces(x)))
    x += 1
Next
sb.AppendLine()
' To check the result (it is useful only if the output window has fixed space font)'
sb.Append("12345678901234567890123456789012345678901234567890123456789012345678901234567890")
Console.WriteLine(sb.ToString())
于 2013-05-08T11:48:49.190 回答
0

您可以使用String.Join来完成您的要求,

String.Join(Space(9), receiptText.Split(Space(1)))
于 2013-05-08T11:23:50.327 回答
0

如果我理解得很好,您需要将您的值连接起来并具有特定的长度。这很容易通过使用format函数和PadLeft/来完成PadRight

首先,您将所有内容都放在格式字符串中。但是每个变量都被传递给一个填充函数。

String strFinalResult = String.Format("{0}{1}{2}", str1.PadRight(9), str2.PadRight(6), str3.PadRight(7));

PadRight 函数中的数字是字符串的总长度。因此,如果您的变量是“abc”并且您调用 str.PadRight(9),您将获得右侧有 6 个空格的“abc”。

希望能帮助到你!

编辑 我的答案是在 C# 中,但由于它是 String 对象,我很确定它在 VB.NET 中可用

编辑 2 如果您希望您的字符串在开头和结尾都有填充,您可以使用 PadRight 和 PadLeft。

于 2013-05-08T11:38:53.147 回答