Skip to content

Instantly share code, notes, and snippets.

@rubenroques
Last active April 29, 2018 16:03
Show Gist options
  • Save rubenroques/95d779ece4a5ef70bcbb to your computer and use it in GitHub Desktop.
Save rubenroques/95d779ece4a5ef70bcbb to your computer and use it in GitHub Desktop.
Fuzzy String Search in Swift
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
@vanakema
Copy link

Shouldn't the block for caseSensitive be

if !caseSensitive {
    originalString = originalString.lowercaseString;
    stringToSearch = stringToSearch.lowercaseString;
}

@rubenroques
Copy link
Author

Fixed, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment