I've just completed an exercise in which I had to create a program that searches for a string within another bigger string.
If the substring exists then it is outputted to confirm and the starting index is given where the first character can be found.
Aside from printf
and scanf
, I am not allowed to use any other functions unless I write them myself.
My code works, however I'm concerned that I've written far more code than is necessary. WITHOUT using pointers (something I'll learn next), could I have considerably cut down the amount of code I wrote?
#include <stdio.h>
#include <stdbool.h>
int findString(char mom[], char babe[]);
int stringLength(const char string[]);
bool equalStrings(const char s1[], const char s2[]);
int main(void)
{
char mommy[80];
char baby[80];
int index;
printf("Which string do you want to search?\n");
scanf("%s", mommy);
printf("What do you want to search for?\n");
scanf("%s", baby);
index = findString(mommy, baby);
if(index >= 0)
printf("Yup, baby was found in mommy at index %i\n", index);
else
printf("Sorry, baby not found\n");
return 0;
}
int findString(char mom[], char babe[])
{
int index, i, j;
int momLength = stringLength(mom);
int babeLength = stringLength(babe);
char test[babeLength + 1];
for(i = 0; i <= babeLength-1; i++)
{
for(j = 0; j <= momLength; j++)
{
if(babe[i] == mom[j])
{
test[i] = babe[i];
if(babe[0] == mom[j])
index = j;
}
}
}
test[babeLength] = '\0';
if(equalStrings(test, babe) == true)
return index;
else
return -1;
}
int stringLength(const char string[])
{
int count = 0;
while(string[count] != '\0')
count++;
return count;
}
bool equalStrings(const char s1[], const char s2[])
{
int i = 0;
bool areEqual;
while(s1[i] == s2[i] && s1[i] != '\0'){
i++;
if(s1[i] == '\0' && s2[i] == '\0')
{
areEqual = true;
}
else
{
areEqual = false;
}
}
return areEqual;
}
strstr()
source code can be found online, I'd give that a look. \$\endgroup\$