Separate the new string that the new string contains the string in old string

61 Views Asked by At

I am newbie in programming and would like to ask if I could separate the string below. I am using Visual Basic. Basically I have two string below :

String 1 : gOldStr= TEDDYBEARBLACKCAT

String 2 = gNewStr= BLACKCATWHITECAT

I wanted to separated the string 2 by looking the exact value in String 1

so that I have String2 that is part of string 1 = BLACKCAT

String 2 that is new = WHITECAT

I have tried below script but it doesn't work all the time. Could suggest me the better logic? Thanks2

For i=1 to Len(gOldStr)
        TempStr = Left$(gNewStr,i) 
        Ctr1 = InStr(gOldStr, TempStr)
        gTemporary = Mid$(gOldStr,Ctr1)

        gTemporary = Trim(gTemporary)

        Ctr2 = StrComp(gOldStr, gTemporary)
        If Ctr2=1 Then
                gTemporary2 = Replace(gNewStr,gTemporary,"")
                Exit For
        End If
Next i 
1

There are 1 best solutions below

4
ib11 On BEST ANSWER

If the common part is always at the end of the first one and at the beginning of the 2nd one, you could look from the end, like this:

Dim strMatchedWord As String
For i=1 to Len(gOldStr)
    If i>Len(gNewStr) Then Exit For  'We need this to avoid an error
    Test1 = Right$(gOldStr, i)
    Test2 = Left$(gNewStr, i)

    If Test1 = Test2 Then
        strMatchedWord = Test1     'Store your match is Test1
    End If
Next
Debug.Print strMatchedWord 'Once the loop finishes it contains the longest match 

I modified the code so that the loop does not exit until it went through the full string. This way it will get you the longest match by the end of the loop.