Home > Software engineering >  How To Check if a Partial String Exist in Another Partial of a String?
How To Check if a Partial String Exist in Another Partial of a String?

Time:07-21

I have the following example:

String 1 = "AA.BB.CD.XY.D1"

String 2 = "FF.GG.AA.XYZ.12"

I need a statement that returns TRUE if any partial of string 1 is found in string 2, which in my above example, it should return TRUE because both strings contain AA. Note that order and length of each string is random. HOWEVER, the . operator is guaranteed to be there, separating each string into sub parts.

CodePudding user response:

In order to use it as a Function: (note that it will match XY in XYZ. That's OK?)

Option Explicit

Sub fnTest()
    Dim str1 As String
    Dim str2 As String
    
    str1 = "AA.BB.CD.XY.D1"
    str2 = "FF.GG.AA.XYZ.12"
    
    MsgBox fnFindStrInStr(str1, str2)
    
End Sub

Function fnFindStrInStr(ByVal str1 As String, ByVal str2 As String) As Boolean

    Dim intSplit As Integer


    For intSplit = 0 To Len(str1) - Len(VBA.Replace(str1, ".", ""))-1
        If InStr(str2, Split(str1, ".")(intSplit)) > 0 Then
            fnFindStrInStr = True
            Exit For
        End If
    Next

End Function
  • Related