将字符串格式化为较小的部分,并在第二个字符串之前添加空格

时间:2019-05-20 20:40:40

标签: vb.net

我在应用程序中有特定要求,每行可用空间有2个字符串和30个字符。

第一个字符串通常为20个以上字符,如果超过30个字符,我需要插入换行符(打印新行)并添加空格,以便第二个字符串位于右侧。

如果我有以下两个字符串:

function array_orderby() {

    $args = func_get_args();
    $data = array_shift( $args );

    foreach ( $args as $n => $field ) :

        if ( is_string( $field ) ) {

            $tmp = array();

            foreach ( $data as $key => $row ) {
                $tmp[ $key ] = $row[ $field ];
            }

            $args[ $n ] = $tmp;

        }

    endforeach;

    $args[] = &$data;
    call_user_func_array( 'array_multisort', $args );

    return array_pop( $args );

}

这是最终结果的样子:

Dim stringNumberOne as String = "string1string1string1string1string1string1string1string1string1string1 "
Dim stringNumberTwo as String = "1,00"

因为这应该写在POS打印机上,所以我需要为每个新行添加string1string1string1string1string 1string1string1string1string1strin g1 1,00 ,因此代码应如下所示:

mstrStringToPrint &= ControlChars.NewLine

我如何在vb.net中实现这一目标?

2 个答案:

答案 0 :(得分:0)

尝试一下。鉴于规格:

Dim maxLengh As Integer = 30
Dim line1 = "string1string1string1string1string1string1string1string1string1string1"
Dim line2 = "1,00"
  • 一个字符串,分为 MaxLength 个部分。
  • 如果零件长度为= MaxLength,请添加换行符和回车符。
  • 如果部件长度为< MaxLength,请添加第二行填充空白,以将字符串填充到MaxLength(如果它可以包含第二行)。
  • 如果第一个字符串可以用MaxLength精确地切片,或者最后一个切片不能包含已经存在的内容+第二行,则添加一个新字符串,并在(MaxLength - [second line].Length)处填充空白

Dim lines As List(Of String) = New List(Of String)()

Dim pos As Integer = 0
While pos < line1.Length
    Dim part = If(pos + maxLength < line1.Length, maxLength, line1.Length - pos)
    lines.Add(line1.Substring(pos, part) & If(part = maxLength, ControlChars.NewLine, ""))
    pos += maxLength
End While
If (lines.Last().Length + line2.Length) < maxLength Then
    lines(lines.Count - 1) = lines.Last() & line2.PadLeft(maxLength - lines.Last().Length, " "c)
Else
    lines.Add(line2.PadLeft(maxLength - line2.Length, " "c))
End If

答案 1 :(得分:0)

我可能会做类似的事情

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim stringNumberOne As String = "string1string1string1string1string1string1string1string1string1string1 "
    Dim stringNumberTwo As String = "1,00"
    Dim NewString As String = String.Empty
    Dim i As Integer = 1
    For Each c As Char In stringNumberOne
        If i = 30 Then
            NewString &= c & Environment.NewLine
            i = 0
        Else
            NewString &= c
            i += 1
        End If
    Next
    NewString = NewString & Environment.NewLine & stringNumberTwo.PadLeft(30, " ")
End Sub

我不确定您要如何处理最后一行,此代码会在将30个字符填充空格之前添加换行符。