How to merge two strings based on shared suffix and prefix in VB.NET

1 Answer

0 votes
Imports System

Module Module1

    Public Function MergeOnOverlap(a As String, b As String) As String
		Dim lenA As Integer = a.Length
		Dim lenB As Integer = b.Length

		Dim maxPossibleverlapLen As Integer = Math.Min(lenA, lenB)

		Dim overlap As Integer = 0

		' Try longest overlap first
		For length As Integer = maxPossibleverlapLen To 1 Step -1
			If String.Compare(a, lenA - length, b, 0, length) = 0 Then
				overlap = length
				Exit For
			End If
		Next

		Return a & b.Substring(overlap)
	End Function

    Sub Main()
        Dim a = "fantasy time travel technology"
        Dim b = "technology extraterrestrial life"

        Dim merged = MergeOnOverlap(a, b)
        
		Console.WriteLine(merged)
    End Sub

End Module



' run:
'
' fantasy time travel technology extraterrestrial life
'

 



answered Jan 23 by avibootz
...