分隔新字符串,新字符串包含旧字符串中的字符串

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

我是编程新手,想请问能否将下面的字符串分开。我正在使用 Visual Basic。基本上我在下面有两个字符串:

字符串 1:gOldStr= TEDDYBEARBLACKCAT

字符串 2 = gNewStr= BLACKCATWHITECAT

我想通过查找字符串 1 中的确切值来分隔字符串 2

这样我就有了 String2,它是字符串 1 的一部分 = BLACKCAT

新字符串 2 = WHITECAT

我已经尝试了下面的脚本,但它并不总是有效。可以建议我更好的逻辑吗?谢谢2

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 

如果公共部分总是在第一个结尾和第二个开头,你可以从最后看,像这样:

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 

我修改了代码,使循环在遍历整个字符串之前不会退出。这样它会在循环结束时为您提供最长的匹配。