-
-
Save bradclawsie/f1a8259152215b228a83 to your computer and use it in GitHub Desktop.
ss.c
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int ss(char *n, char *h) { | |
const size_t n_len = strlen(n); | |
// empty needle is in haystack | |
if (n_len == 0) return 1; | |
const size_t h_len = strlen(h); | |
// needle cannot be longer than haystack | |
if (n_len > h_len) return 0; | |
// equal lengths must have equal values | |
if (n_len == h_len) return (0 == strncmp(n,h,n_len)); | |
char *c = h; | |
while (*c) { | |
size_t c_l = strlen(c); | |
// needle now bigger than substring | |
if (c_l < n_len) return 0; | |
// c has len at least n_len, try an n_len compare | |
if (0 == strncmp(c,n,n_len)) return 1; | |
c++; | |
} | |
return 0; | |
} | |
int main(void) { | |
char *needle = "ays"; | |
char *haystack = "haystack"; | |
const int is_ss = ss(needle,haystack); | |
printf("is needle '%s' in haystack '%s' ? %d\n",needle,haystack,is_ss); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment