史萊姆論壇

史萊姆論壇 (http://forum.slime.com.tw/)
-   程式語言討論區 (http://forum.slime.com.tw/f76.html)
-   -   字串的相似度 (教學) (http://forum.slime.com.tw/thread209678.html)

mini 2007-07-02 03:43 PM

字串的相似度 (教學)
 
在寫程式時 或許會用到
這裡提供出來給大家做參考
範例是用 VB寫的

比較 Str2 與 Str1 的相似度 (比對字串的相似度),預設至少三個字母同才為一個 單字
語法:

Private Function StrComp_Percentage(Str1 As String, Str2 As String, Optional iSingleWord = 3) As Integer
Dim i As Integer, j As Integer, c As Integer, sw As Integer

    On Error GoTo COMP_END
   
    If StrComp(Str1, Str2, vbTextCompare) = 0 Then
        StrComp_Percentage = 100
        Exit Function
    End If
   
    If Len(Str1) > Len(Str2) Then
    Dim stmp As String
        stmp = Str1
        Str1 = Str2
        Str2 = stmp
    End If
   
    j = 1
    For i = 1 To Len(Str1)
        sw = iSingleWord
        Do While StrComp(Mid(Str1, i, 1), Mid(Str2, j, 1), vbTextCompare) = 0
            sw = sw - 1
            If sw = 0 Then
                c = c + iSingleWord
            ElseIf sw < 0 Then
                c = c + 1
            End If
            i = i + 1
            j = j + 1
            If i > Len(Str1) Then GoTo COMP_END
        Loop
       
        sw = InStr(j, Str2, Mid(Str1, i, 1), vbTextCompare)
        If sw > 0 Then
            j = sw
        Else
            j = i
        End If
        j = j + 1
    Next
   
COMP_END:
    StrComp_Percentage = Round(c / Len(str2) * 100)
   
End Function

範例:
語法:

str1 = "http://cartoonphoto.591ac.com/photo/co2a/thumbnails/co2a_01.jpg"
str2 = "http://cartoonphoto.591ac.com/photo/co2a/images/co2a_01.jpg"
Label1.Caption = StrComp_Percentage(Str1, Str2)

str1 = "http://www.sinaimg.cn/dongman/pic/jxms_07_06_26/U2264P55T4D122733F50DT20070626114316_160small.jpg"
str2 = "http://www.sinaimg.cn/dongman/pictcol/2007-06-26/U2264P55T4D122733F50DT20070626114316_600small.jpg"
Label1.Caption = StrComp_Percentage(Str1, Str2)

str2 = "http://www.sinaimg.cn/dongman/pic/jxms_07_06_26/U2264P55T4D122733F50DT20070626114316.jpg"
Label1.Caption = StrComp_Percentage(Str1, Str2)

分別得到:
84、81、90 (單位是百分比)


所有時間均為台北時間。現在的時間是 04:42 PM

Powered by vBulletin® 版本 3.6.8
版權所有 ©2000 - 2024, Jelsoft Enterprises Ltd.

『服務條款』

* 有問題不知道該怎麼解決嗎?請聯絡本站的系統管理員 *


SEO by vBSEO 3.6.1