VB.NET文本框删除最后一个破折号

时间:2018-04-30 14:56:09

标签: vb.net loops

如何在输入代码后删除最后添加的-
所有-都会自动添加。

这是我的代码:

Dim strKeyTextField As String = txtAntivirusCode.Text
Dim n As Integer = 5
Dim intlength As Integer = txtAntivirusCode.TextLength

While intlength > 4
    If txtAntivirusCode.Text.Length = 5 Then
        strKeyTextField = strKeyTextField.Insert(5, "-")
    End If

    Dim singleChar As Char
    singleChar = strKeyTextField.Chars(n)

    While (n + 5) < intlength
        If singleChar = "-" Then
            n = n + 6

            If n = intlength Then
                strKeyTextField = strKeyTextField.Insert(n, "-")
            End If
        End If
    End While

   intlength = intlength - 5
End While

'' Define total variable with dashes
txtAntivirusCode.Text = strKeyTextField
'sets focus at the end of the string
txtAntivirusCode.Select(txtAntivirusCode.Text.Length, 0)

输出为:XXXXX-XXXXX-XXXXX-XXXXX-XXXXX-

我想要的是什么:XXXXX-XXXXX-XXXXX-XXXXX-XXXXX

2 个答案:

答案 0 :(得分:2)

您可以删除字符串中的最后一个字符:

txtAntivirusCode.Text = strKeyTextField.Substring(0, strKeyTextField.Length - 1)

txtAntivirusCode.Text = strKeyTextField.Remove(strKeyTextField.Length - 1)

txtAntivirusCode.Text = strKeyTextField.Trim({" "c, "-"c})

txtAntivirusCode.Text = strKeyTextField.TrimEnd(CChar("-"))

如果字符串末尾有可能在子字符串和/或删除之前使用.Trim()

答案 1 :(得分:2)

从删除最后一个&#34; - &#34;是不添加最后的&#34; - &#34;,例如:

Dim s = "ABCDE-FGHIJKLMNOPQRSTUVWXYZ"

Dim batchSize = 5
Dim nBatches = 5
Dim nChars = nBatches * batchSize

' take out any dashes
s = s.Replace("-", "")
' make sure there are not too many characters
If s.Length > nChars Then
    s = s.Substring(0, nChars)
End If

Dim sb As New Text.StringBuilder

For i = 1 To s.Length
    sb.Append(s.Chars(i - 1))
    If i Mod batchSize = 0 AndAlso i <> nChars Then
        sb.Append("-")
    End If
Next

Console.WriteLine(sb.ToString())

Console.ReadLine()

输出:

ABCDE-FGHIJ-KLMNO-PQRST-UVWXY