Skip to content

Instantly share code, notes, and snippets.

@jdb8
Created November 24, 2012 20:42
Show Gist options
  • Save jdb8/4141338 to your computer and use it in GitHub Desktop.
Save jdb8/4141338 to your computer and use it in GitHub Desktop.
Function to find the first occurence of a string within another
#include <stdio.h>
#include <string.h>
const char *strfind(const char *s, const char *f);
int main(int argc, char **argv){
const char *s = argv[1];
const char *f = argv[2];
printf("%s, %s, %s\n", s, f, strfind(s, f));
return 0;
}
// Function to find the first occurence of a string within another
// Returns a pointer if found, NULL otherwise
const char *strfind(const char *s, const char *f){
int i, j, sLength, fLength, match;
const char *found = NULL;
sLength = strlen(s);
fLength = strlen(f);
// Loop through each character in f
for (i = 0; i < fLength; i++){
// For each character in s, check if we have an initial match
for (j = 0; j < sLength; j++){
// If we have a match, move to the next character, otherwise break
if (f[i+j] == s[j]){
match = 1;
} else {
match = 0;
break;
}
}
// Set found to the first character that was matched and break
if (match) {
found = &f[i];
break;
}
}
return found;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment