2015-03-31 282 views
0

我遇到問題了。我必須從XML中獲得與textBox中鍵入的字符串相同的值。我需要做的是讓程序更「智能」,這意味着,如果我輸入「kraków」而不是「Kraków」,程序應該找到位置。XML中不完全匹配

示例代碼:

public static IEnumerable<XElement> GetRowsWithColumn(IEnumerable<XElement> rows, String name, String value) 
{ 
    return rows 
     .Where(row => row.Elements("col") 
      .Any(col => 
       col.Attributes("name").Any(attr => attr.Value.Equals(name)) 
       && col.Value.Equals(value))); 
} 

如果鍵入「克拉科夫」然後我從XML不錯的反響,但是當我鍵入「克拉科夫」沒有匹配。我該怎麼辦?

如果我可以再問一個問題,我該如何提示如谷歌有?如果你輸入「progr」,google會顯示你「編程」的例子。

回答

0

只是做一個比較字符串的函數。你可以使用任何你想要的標準

... 
    col.Attributes("name").Any(attr => AreEquivelant(attr.Value, name)) 
    ... 

private static bool AreEquivelant(string s1, string s2) 
{ 
    //compare the strings however you want 
} 
+0

可惜這不是解決辦法,怎麼也有像「別爾斯克 - 比亞拉」「新維斯城市」,當你鍵入沒有第二上,和「 - 」沒有匹配。 – 2015-03-31 20:59:57

-1

你會找到一個距離。距離是兩個詞之間的差異。你可以使用Levenshtein這個。

維基百科:

在信息理論和計算機科學,Levenshtein距離度量是用於測量兩個序列之間的差異的字符串。非正式地,兩個單詞之間的Levenshtein距離是將一個單詞換成另一個單詞所需的單字符編輯(即插入,刪除或替換)的最小數量。

基本用例:

static void Main(string[] args) 
{ 
    Console.WriteLine(Levenshtein.FindDistance("Alois", "aloisdg")); 
    Console.WriteLine(Levenshtein.FindDistance("Alois", "aloisdg", true)); 
    Console.ReadLine(); 
} 

輸出

3 
2 

值越小,越好的比賽。 對於你的例子,你可以使用它,如果匹配比某些事情(比如2)低,你就得到了一個有效的匹配。

我做了一個here

代碼:

public static int FindDistance(string s1, string s2, bool forceLowerCase = false) 
{ 
    if (String.IsNullOrEmpty(s1) || s1.Length == 0) 
     return String.IsNullOrEmpty(s2) ? s2.Length : 0; 
    if (String.IsNullOrEmpty(s2) || s2.Length == 0) 
     return String.IsNullOrEmpty(s1) ? s1.Length : 0; 
    // not in Levenshtein but I need it. 
    if (forceLowerCase) 
    { 
     s1 = s1.ToLowerInvariant(); 
     s2 = s2.ToLowerInvariant(); 
    } 
    int s1Len = s1.Length; 
    int s2Len = s2.Length; 
    int[,] d = new int[s1Len + 1, s2Len + 1]; 
    for (int i = 0; i <= s1Len; i++) 
     d[i, 0] = i; 
    for (int j = 0; j <= s2Len; j++) 
     d[0, j] = j; 
    for (int i = 1; i <= s1Len; i++) 
    { 
     for (int j = 1; j <= s2Len; j++) 
     { 
      int cost = Convert.ToInt32(s1[i - 1] != s2[j - 1]); 
      int min = Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1); 
      d[i, j] = Math.Min(min, d[i - 1, j - 1] + cost); 
     } 
    } 
    return d[s1Len, s2Len]; 
} 
+0

謹慎解釋downvote? – aloisdg 2015-03-31 21:11:06

0

,而你使用

.ToUpper() 

爲你的字符串你可以比較你的價值。

爲了得到這些提示,谷歌有,你可能需要正則表達式。 詳細請看這裏:

Learning Regular Expressions