I've just done a C exercise from a book, the object of which was to write my own version of a function which returns a pointer to the first incidence of one string within another, or NULL if there is no match. It works, but I just get the feeling it's bloated and could be a lot neater. In particular I'm unhappy about the levels of nesting in the function. Should I be? Any advice? My apologies for the indentation, I used tabs and I couldn't work out how to quickly change tab indents to spaces in Visual Studio C++ for posting to a forum.
Code:
#include <stdio.h>
#include <string.h>
char * string_in(char * str1, char * str2);
int main(void)
{
char string[200];
char match_string[200];
char * result;
printf("Enter a string to search: ");
while (gets(string) && string[0] != '\0')
{
printf("Enter a string to search for: ");
do
{
if (strlen(gets(match_string)) > strlen(string))
printf("\nMust not exceed length of first string. Try again: ");
}
while (strlen(match_string) > strlen(string));
result = string_in(string, match_string);
if (result)
printf("String was found at position %d", (result - string + 1));
else
printf("String was not found.\n\n");
printf("\nEnter another string to search: ");
}
return 0;
}
char * string_in(char * s1, char * s2)
{
char first_ch = s2[0];
int i, j, match = 0;
int len_s1 = strlen(s1);
int len_s2 = strlen(s2);
for (i = 0; i <= (len_s1 - len_s2); i++)
{
if (s1[i] == first_ch)
{
match = 1;
for (j = 1; j < len_s2; j++)
{
if (s1[i + j] != s2[j])
{
match = 0;
break;
}
}
}
if (match == 1)
break;
}
if (match == 1)
return (s1 + i);
else
return NULL;
}