首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >检查字符串是否有相同的数字

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

Stack Overflow用户
提问于 2014-11-28 10:26:11
回答 2查看 536关注 0票数 0

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-28 10:33:12

请参阅下面的代码片段:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2014-12-01 17:29:16

这个答案类似于接受的答案,但不会在内存中创建许多临时字符串。

代码语言:javascript
复制
'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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27186629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档