How to compare array to array using VBScript?

后端 未结 1 914
暗喜
暗喜 2021-01-17 03:08

I would like to check a data in my file exist or not in an array data that I have. It will return 1 and 0 if its exit or not. Inside my file is like this:

2j2H4F6         


        
相关标签:
1条回答
  • 2021-01-17 03:59

    For one thing, [2w fr 5k 2j 0w] is not a valid array definition in VBScript. If you want to define an array with these 5 string elements you need to do it like this:

    Array("2w", "fr", "5k", "2j", "0w")
    

    Also, StrComp() is for comparing a string to another string. It does not support comparing a string to an array. For comparing a string to each element of an array you need a loop. How to build that loop depends on the result you want to achieve, though.

    Looking at your code it seems you want to find a match in 2j2H4..., but not in w2j2H..., so simply using InStr() probably won't work for you. In that case you could use an inner loop for the comparison:

    ref = Array("2w", "fr", "5k", "2j", "0w")
    For i = 1 To Len(strFBString) Step 2
        For Each s In ref
            If Mid(strFBString, i, 2) = s Then
                '...
            End If
        Next
    Next
    

    But like I already said, details depend on the desired end result. If you want to check if your input string contains any of the array values you could do something like this:

    ref   = Array("2w", "fr", "5k", "2j", "0w")
    found = False
    For i = 1 To Len(strFBString) Step 2
        For Each s In ref
            If Mid(strFBString, i, 2) = s Then
                found = True
                Exit For
            End If
        Next
    Next
    

    If on the other hand you wanted to check if your input string contains all of the reference strings you'd probably do something like this instead:

    ref   = Array("2w", "fr", "5k", "2j", "0w")
    For Each s In ref
        found = False
        For i = 1 To Len(strFBString) Step 2
            If Mid(strFBString, i, 2) = s Then
                found = True
                Exit For
            End If
        Next
        If Not found Then Exit For
    Next
    

    You could also use an entirely different approach, like putting your data in a dictionary:

    data = CreateObject("Scripting.Dictionary")
    For i = 1 To Len(strFBString) Step 2
        data(Mid(strFBString, i, 2)) = True
    Next
    

    Using that approach you could check if the data contains any of the reference values like this:

    found = False
    For s In Array("2w", "fr", "5k", "2j", "0w")
        If data.Exists(s) Then
            found = True
            Exit For
        End If
    Next
    

    or check if the data contains all of the reference values like this:

    found = True
    For s In Array("2w", "fr", "5k", "2j", "0w")
        If Not data.Exists(s) Then
            found = False
            Exit For
        End If
    Next
    
    0 讨论(0)
提交回复
热议问题