Last active
August 29, 2015 14:25
-
-
Save ork/fef0dcdecbbdfe3c4982 to your computer and use it in GitHub Desktop.
Fuzzy string search
This file contains hidden or 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
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <stdbool.h> | |
| bool fuzzy_search(const char *needle, const char *haystack) | |
| { | |
| size_t hlen = strlen(haystack); | |
| size_t nlen = strlen(needle); | |
| if (nlen > hlen) { | |
| return false; | |
| } | |
| if (nlen == hlen) { | |
| return strcmp(needle, haystack) == 0; | |
| } | |
| for (size_t i = 0, j = 0; i < nlen; ++i) { | |
| char nch = needle[i]; | |
| while (j < hlen) { | |
| if (haystack[j++] == nch) { | |
| goto resume; | |
| } | |
| } | |
| return false; | |
| resume: ; | |
| } | |
| return true; | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| char *needle = NULL, | |
| *haystack = NULL; | |
| size_t needle_len = 0; | |
| ssize_t read; | |
| if (argc < 2) { | |
| fprintf(stderr, "Usage: %s <HAYSTACK>\n", argv[0]); | |
| return 1; | |
| } | |
| haystack = argv[1]; | |
| while ((read = getline(&needle, &needle_len, stdin)) != -1) { | |
| needle[--read] = '\0'; | |
| printf("Needle: '%s'\tHaystack: '%s'\tFound: %d\n", | |
| needle, haystack, fuzzy_search(needle, haystack)); | |
| } | |
| free(needle); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment