Skip to content

Instantly share code, notes, and snippets.

@ravishi
Created August 4, 2010 19:06
Show Gist options
  • Save ravishi/508613 to your computer and use it in GitHub Desktop.
Save ravishi/508613 to your computer and use it in GitHub Desktop.
Uma função strpos feita do zero
/**
* Uma função strpos feita do zero.
*/
#include <stdio.h>
/**
* Procura a string b na string a.
*
* Retorna -1 se `b` não for encontrada em `a`, ou o índice da
* primeira ocorrência de b em a.
*/
long strpos(const char *a, const char *b)
{
const char *x, *y;
x = a;
y = b;
while (*x != '\0') {
y = b;
while (*x == *y && *y != '\0') {
x++;
y++;
}
if (*y == '\0') {
return (long) (x - a - (y - b));
}
else {
x++;
}
}
return -1;
}
int main(int *args, char *argv[])
{
const char *a, *b;
long pos;
a = argv[1];
b = argv[2];
pos = strpos(a, b);
if (pos < 0) {
printf("`%s' not found in `%s'\n", b, a);
}
else {
printf("`%s' found in `%s' at position %ld\n", b, a, pos);
}
return 0;
}
@ravishi
Copy link
Author

ravishi commented Aug 3, 2011

Wow, this version is beautiful. Simpler and cleaner. Thanks to my teacher at the university.

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