检查字符串是否有相同的数字

时间:2014-11-28 10:26:12

标签: vb.net visual-studio-2012

我要求我的用户输入一个4-6位数的PIN码。我想确保用户无法输入0000或11111或333333.如何检查4个连续相同数字的字符串?我正在使用vb.net。

2 个答案:

答案 0 :(得分:1)

请参阅下面的代码段:

Sub Main()
    Dim a As String = "001111"
    Dim b As String = "1123134"
    Dim c As String = "1111"

    Console.WriteLine(CheckConsecutiveChars(a, 4)) 'True => Invalid Pin
    Console.WriteLine(CheckConsecutiveChars(b, 4)) 'False => Valid Pin
    Console.WriteLine(CheckConsecutiveChars(c, 4)) 'True => Invalid Pin
    Console.ReadLine()
End Sub


'maxnumber = maximum number of identical consecutive characters in a string
Public Function CheckConsecutiveChars(ByVal j As String, ByVal maxNumber As Integer) As Boolean

    Dim index As Integer = 0
    While ((index + maxNumber) <= j.Length)
        If (j.Substring(index, maxNumber).Distinct.Count = 1) Then
            Return True
        End If
        index = index + 1
    End While
    Return False

End Function

方法String.Distinct.Count()计算字符串中不同字符的数量。您将数字转换为字符串并测试不同字符的数量。如果结果为1,则用户输入相同的数字。

注意:如果您使用的是Substring,则必须先检查字符串的长度(足够长)以避免异常。

答案 1 :(得分:0)

此答案与接受的答案类似,但不会在内存中创建大量临时字符串。

'maxnumber = maximum number of identical consecutive characters in a string
Public Function HasConsecutiveChars(ByVal j As String, ByVal maxNumber As Integer) As Boolean

    Dim result As Boolean = False
    Dim consecutiveChars As Integer = 1
    Dim prevChar As Char = "x"c

    For Each c in j
        If c = prevChar Then
            consecutiveChars += 1
            If consecutiveChars >= maxNumber Then
                result = True
                Exit For
            End If
        Else
            consecutiveChars = 1
        End If

        prevChar = c
    Next

    Return result

End Function