VB.NET текстовое поле удалить последнюю черту - PullRequest
0 голосов
/ 30 апреля 2018

Как удалить последние -, добавленные после ввода кода.
Все - добавляются автоматически.

Вот мой код:

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 голосов
/ 30 апреля 2018

Другой способ удалить последний «-» - не добавлять последний «-», например:

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
0 голосов
/ 30 апреля 2018

Вы можете просто удалить последний символ в строке:

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() перед Подстрокой и / или Удалить

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...