Re: Evaluation of C program



morphex@xxxxxxxxx wrote:
I'm a python programmer that's started to play a bit with C as I'll
probably have to make C extensions eventually.. I made this little
program that I'd like to get feedback on, it's basically a find
substring and return pointer to it function and tests for it..

Could this be done better/differently? Is anything fundamentally
wrong?

---

#include <stdio.h>

char *find_substring(char *substring, char *string) {
int index_string, index_substring;
for (index_string = 0; string[index_string] != 0; index_string++) {
index_substring = 0;
do {
if (substring[index_substring] == 0)
goto success;
if (string[index_string + index_substring] !=
substring[index_substring])
goto next;
} while (++index_substring);
success:
return &string[index_string];
next: ;
}
return 0;
}

int main() {
if(find_substring("test", "this is a test"))
printf("Found test in string!\n");

return 0;
}

Here is how I would do it.


--- Source Text ---

#include <stdio.h>
#include <string.h>


/* Returns the starting index of pattern in s or -1 if not found. */

int position(const char *pattern, const char *s)
{
int j, k, plen, slen, res;

plen = strlen(pattern);
slen = strlen(s);
res = -1;
j = 0;
while ((res < 0) && (j + plen < slen)) {
k = 0;
while ((k < plen) && (pattern[k] == s[j + k])) { k++; }
if (k == plen) { res = j; }
j++;
}
return res;
}


int main(void)
{
char s[] = "Hello there!";
char pattern[] = "there";
int pos;

pos = position(pattern, s);
if (pos < 0) {
printf("\"%s\" does not contain \"%s\".\n", s, pattern);
} else {
printf("\"%s\" contains \"%s\" starting at index %d.\n",
s, pattern, pos);
}
return 0;
}

--- End Of Source Text ---


August

--
I am the "ILOVEGNU" signature virus. Just copy me to your
signature. This email was infected under the terms of the GNU
General Public License.
.



Relevant Pages