如何在输入代码后删除最后添加的-
。
所有-
都会自动添加。
这是我的代码:
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
答案 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