簡單的獲得兩個字串相似性的代碼

來源:互聯網
上載者:User

自己瞎想出來的,每個字元都有一個權值,字串前面1/3的權值是3,中間1/3是2,最後1/3是1。總權值就是所有字元的權值相加。然後兩個字串從開始一個一個字元的對比,相同的就加上這個字元的權值。最後得到的權值乘以100去除總權值,得到的就是一個0-100的基本權值。

然後用:
(兩個字串長度差 * 40) div 短字串長度
得到一個差值(如果 兩個字串長度差 > 短字串長度 直接設差值為40)

最後 基本權值-差值 就得到相似性:

function strSimilar(str1, str2 : string):integer;
var
  rate : integer;
  len, i : integer;
  rates, tot_rates : integer;
  division : integer;
begin
  rate := 3;

  if(length(str1) > length(str2)) then
  begin
    len := length(str2)
    division := length(str1) - len;
  end
  else
  begin
    len := length(str1);
    division := length(str2) - len;
  end;
  if(division > len) then
    division = 40
  else
    division := (division * 40) div len;

  tot_rates := 0;
  rates := 0;

  for i := 1 to len do
  begin
    if(i > ((len div 3) * 2)) then
      rate := 1
    else if (i > (len div 3)) then
      rate := 2;

    tot_rates := tot_rates + rate;
    if(LowerCase(MidStr(str1,i,1)) = LowerCase(MidStr(str2,i,1))) then
      rates := rates + rate;
  end;

  result := (rates * 100) div tot_rates;
end;

這個代碼還需要完善,最後需要能夠根據字串中字元差、長度差得到一個0-100的像素度值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.