Last active
April 29, 2018 16:03
-
-
Save rubenroques/95d779ece4a5ef70bcbb to your computer and use it in GitHub Desktop.
Fuzzy String Search in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func fuzzySearch(var originalString: String, var stringToSearch: String, caseSensitive: Bool = false)->Bool { | |
if countElements(originalString)==0 || countElements(stringToSearch)==0 { | |
return false | |
} | |
if countElements(originalString) < countElements(stringToSearch) { | |
return false | |
} | |
if !caseSensitive { | |
originalString = originalString.lowercaseString | |
stringToSearch = stringToSearch.lowercaseString | |
} | |
var searchIndex : Int = 0 | |
for charOut in originalString{ | |
for (indexIn,charIn) in enumerate(stringToSearch) { | |
if indexIn==searchIndex{ | |
if charOut==charIn{ | |
searchIndex++ | |
if searchIndex==countElements(stringToSearch) { | |
return true; | |
} | |
else { | |
break | |
} | |
} | |
else { | |
break | |
} | |
} | |
} | |
} | |
return false; | |
} | |
// | |
var myTestString = "NSNumberFormatterPadPosition" | |
//Examples | |
fuzzySearch(myTestString,"NSNumber") //true | |
fuzzySearch(myTestString,"NSNumFormPaPos") //true | |
fuzzySearch(myTestString,"NSXNumber") //false | |
fuzzySearch(myTestString,"nsnumb") // false | |
fuzzySearch(myTestString,"nsnumb", caseSensitive:true) // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shouldn't the block for caseSensitive be