Function WordCompare(word1 As String, word2 As String, Optional weight_towards_front As Boolean = False) As Integer

'Compares two strings and returns a value between 0 and 100 for similarness

If word1 = "" And word2 = "" Then

WordCompare = 0

Exit Function

End If

If word1 = word2 Then

WordCompare = 100

Exit Function

End If

Dim word1_len, word2_len As Integer

word1_len = Len(word1)

word2_len = Len(word2)

Dim n, i, j, k, x, y, eb As Integer

n = 0

i = 0

j = 0

k = 0

x = 0

y = 0

For i = 1 To word1_len

x = i

For j = 1 To word2_len

y = j

k = 0

Do While x <= word1_len And y <= word2_len And Mid(word1, x, 1) = Mid(word2, y, 1)

eb = 1

If weight_towards_front Then

If x < 2 And y < 2 Then

eb = eb + 3

End If

If x < 3 And y < 3 Then

eb = eb + 2

End If

If x < 4 And y < 4 Then

eb = eb + 1

End If

End If

k = k + 1

n = n + (k * k * eb)

x = x + 1

y = y + 1

Loop

Next j

Next i

n = (n * 20) / (word1_len * word2_len)

If n > 100 Then

n = 100

End If

WordCompare = n

End Function

## Wednesday, March 7, 2012

### Compare the simlarity of two strings in Visual Basic

I have adapted this code from some C code I found on the Internet years ago.

Subscribe to:
Post Comments (Atom)

## No comments:

## Post a Comment