Skip to content

Instantly share code, notes, and snippets.

@bradclawsie bradclawsie/ss.c
Created Oct 31, 2014

What would you like to do?
#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;
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
You can’t perform that action at this time.