github.com/zhongdalu/gf@v1.0.0/g/text/gstr/gstr_similartext.go (about) 1 // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 package gstr 8 9 // SimilarText calculates the similarity between two strings. 10 // See http://php.net/manual/en/function.similar-text.php. 11 func SimilarText(first, second string, percent *float64) int { 12 var similarText func(string, string, int, int) int 13 similarText = func(str1, str2 string, len1, len2 int) int { 14 var sum, max int 15 pos1, pos2 := 0, 0 16 17 // Find the longest segment of the same section in two strings 18 for i := 0; i < len1; i++ { 19 for j := 0; j < len2; j++ { 20 for l := 0; (i+l < len1) && (j+l < len2) && (str1[i+l] == str2[j+l]); l++ { 21 if l+1 > max { 22 max = l + 1 23 pos1 = i 24 pos2 = j 25 } 26 } 27 } 28 } 29 30 if sum = max; sum > 0 { 31 if pos1 > 0 && pos2 > 0 { 32 sum += similarText(str1, str2, pos1, pos2) 33 } 34 if (pos1+max < len1) && (pos2+max < len2) { 35 s1 := []byte(str1) 36 s2 := []byte(str2) 37 sum += similarText(string(s1[pos1+max:]), string(s2[pos2+max:]), len1-pos1-max, len2-pos2-max) 38 } 39 } 40 41 return sum 42 } 43 44 l1, l2 := len(first), len(second) 45 if l1+l2 == 0 { 46 return 0 47 } 48 sim := similarText(first, second, l1, l2) 49 if percent != nil { 50 *percent = float64(sim*200) / float64(l1+l2) 51 } 52 return sim 53 }