我要求我的用户输入一个4-6位数字密码密码。我想确保用户不能输入0000、11111或333333。如何检查字符串中的4个连续相同数字?我在用vb.net。
发布于 2014-11-28 10:33:12
请参阅下面的代码片段:
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,则必须首先检查字符串的长度(是否足够长)以避免异常。
发布于 2014-12-01 17:29:16
这个答案类似于接受的答案,但不会在内存中创建许多临时字符串。
'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 Functionhttps://stackoverflow.com/questions/27186629
复制相似问题