根据字符串的长度添加数字

时间:2019-12-30 21:31:27

标签: vb.net

我想要在vb.net中使用类似以下内容的代码,我的问题是在最后一个语句中,我未能从缺失的数字中创建一个等于C的16位数字的字符串。

Dim A as string
Dim B as a string
Dim C as integer
if len(A) = 16 then
   B = A
elseif Len(A) > 16 then
   B = first 16 digits of A, 'ignore the rest if the digits'
elseif len(A) < 16 then
   C = 16 - len(A)
   B = A & digits equal to count of C 'Making Len(B) = 16'
else
end if

1 个答案:

答案 0 :(得分:0)

我使用了.net String类,它是System名称空间中.net Framework的一部分。

String.Length是字符串的属性。它取代了旧的VB6 Len方法。

String.Substring具有多个重载。我在这里使用的那个有2个整数作为参数。第一个是起始索引,第二个是要返回的字符串的长度。

String.PadRight有两个参数。第一个是Integer,它提供新字符串的总长度。第二个字符是提供字符填充的字符。后面的小写c区分了编译器的String和Char文字。

您可以在https://docs.microsoft.com/en-us/dotnet/api/system.string?view=netframework-4.8

看到所有String方法和属性。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim PaddedString As String = Get16String(TextBox1.Text)
    Debug.Print(PaddedString)
End Sub

Private Function Get16String(Input As String) As String
    Dim B As String = ""
    If Input.Length = 16 Then
        B = Input
    ElseIf Input.Length > 16 Then
        B = Input.Substring(0, 16)
    ElseIf Input.Length < 16 Then
        B = Input.PadRight(16, "0"c)
    End If
    Return B
End Function