Created
August 4, 2010 19:06
-
-
Save ravishi/508613 to your computer and use it in GitHub Desktop.
Uma função strpos feita do zero
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
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow, this version is beautiful. Simpler and cleaner. Thanks to my teacher at the university.