调试文本到文件格式

Debug text to file formatting

嘿,我希望简化以下代码,以便输出正确数量的 = 以匹配输出部分的 top/bottom。

示例:

========================================================================
=======================This would be the text here======================
========================================================================

文本这将是此处的文本将是发送给函数的内容。这可以是从 4 个字符到最多 72 个字符的任何内容。我想看看是否有更简单的编码方法,然后是我正在使用的以下方法:

Dim cnt As Integer = 0
Dim ch As Char = ""

For Each c As Char In _tmpDebugArray(0)
    If c = ch Then cnt += 1
Next

cnt = Math.Round((cnt - 72) / 2, 2)

cnt 会给我在调试信息名称的左侧和右侧需要使用的 = 的数量匹配输出部分的 =.

的 top/bottom

示例:

Dim strDebug string = "Bob The Builder"
cnt = 72 - strDebug          '72-15 = 57
cnt = Math.Round(cnt / 2, 2) '57/2 = 29 (28.5 rounded)

所以在上面的例子中 = 左边会有 28 然后调试字符串 Bob The Builder 然后 29 = 在它的右边。虽然根据调试字符串的长度,这里和那里往往会被 1 关闭。

使用固定宽度并在左侧和右侧填充文本可能更容易。

Sub DisplayText(ByVal text As String)

    Const WIDTH As Integer = 72
    Const DISPLAY_CHAR As String = "="c

    Console.WriteLine("".PadLeft(WIDTH, DISPLAY_CHAR))
    Console.WriteLine(text.PadLeft((WIDTH + text.Length) / 2, DISPLAY_CHAR).PadRight(WIDTH, DISPLAY_CHAR))
    Console.WriteLine("".PadLeft(WIDTH, DISPLAY_CHAR))

End Sub

假设您只会以固定宽度的字体查看这些字符串,您可以使用 PadLeftPadRight 将字符串填充到正确的长度。以下函数对任何字符串、填充字符和长度执行此操作。

Function PadStringCentre(str As String, ch As Char, len As Integer) As String
    Dim numLeft As Integer = (len - str.Length) \ 2 + str.Length 
    Dim numRight As Integer = len - str.Length - numRight 
    Return str.PadLeft(numLeft,ch).PadRight(len, ch)
End Function

你可以这样称呼它

Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Label1.Text = PadStringCentre("Bob The Builder", "="c, 72)
End Sub