Guest User

Untitled

a guest
Jun 17th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. /// <summary>
  2. /// This method takes in the attribute and word (key value) that you searching
  3. /// for in LDAP, and generates a "Fuzzy Search" string based on the key and
  4. /// value that is passed in
  5. /// </summary>
  6. /// <param name="word">The value you are searching for</param>
  7. /// <param name="attribute">The key you are searching for</param>
  8. /// <returns>Search String</returns>
  9. private string BuildFuzzySearchString(string word, string attribute)
  10. {
  11. // Create the list of fuzzy search terms
  12. var words = new List<string>();
  13.  
  14. // Add the origingal word in, it could be spelled correctly
  15. words.Add($"({attribute}={word})");
  16.  
  17. // We'll be using a Stringbuilder object to store our fuzzyword mutations
  18. StringBuilder fuzzyWord = null;
  19.  
  20. // Go through and replace each letter with a wildcard, and store in the list
  21. // This will cover a single letter misspelling, or an omitted letter
  22. for(var i=0; i<word.Length; i++)
  23. {
  24. fuzzyWord = new StringBuilder(word);
  25. fuzzyWord[i] = '*';
  26. words.Add($"({attribute}={fuzzyWord.ToString()})");
  27. }
  28.  
  29. // Now slice up the string so that we get results if the user only knows the first 3 or last 3 characters
  30. var minLength = 3;
  31.  
  32. if (word.Length >= minLength)
  33. {
  34. fuzzyWord = new StringBuilder();
  35. fuzzyWord.Append(word.Substring(0, minLength) + "*");
  36. words.Add($"({attribute}={fuzzyWord.ToString()})");
  37.  
  38. fuzzyWord = new StringBuilder();
  39. fuzzyWord.Append(Reverse(Reverse(word).Substring(0, minLength) + "*"));
  40. words.Add($"({attribute}={fuzzyWord.ToString()})");
  41. }
  42.  
  43. // Now if the user doesn't remember how to spell the middle of the word, we want at least twice the minimum length
  44. if (word.Length > (minLength * 2))
  45. {
  46. fuzzyWord = new StringBuilder();
  47. fuzzyWord.Append(word.Substring(0, minLength) + "*");
  48. fuzzyWord.Append(Reverse(Reverse(word).Substring(0, minLength)));
  49. words.Add($"({attribute}={fuzzyWord.ToString()})");
  50. }
  51.  
  52. return string.Join("", words.ToArray());
  53. }
  54.  
  55. /// <summary>
  56. /// Reverses a string
  57. /// </summary>
  58. /// <param name="s">String to be reversed</param>
  59. /// <returns>string except in reverse</returns>
  60. private string Reverse(string s)
  61. {
  62. char[] charArray = s.ToCharArray();
  63. Array.Reverse(charArray);
  64. return new string(charArray);
  65. }
Add Comment
Please, Sign In to add comment