I am working on some string manipulation functions, just out of my own interest. However, I may want to use these functions sometime in future code. I wrote the following to check if a substring exists within a string. I ran into a problem though. My program compares each char in both strings, however it had problems with out of order chars. It would take a long time to explain so I will just give an example:
if checking if “oobar” exists in the string “fooobar” my program would have trouble finding the location of the substrings because it would trip up on the first instances of the char ‘o’
I developed a work around to this, but that’s what it is a work around and not really a solid solution. So I was wondering if anybody could tell me how they would improve the following code (keep in mind I do NOT want to use any additional libraries):
int chksbstr(char *str, char *sbstr)
{
int i, sbstrlen, strlen, p = 0;
for(i = 0; sbstr[i] != '\0'; i++);
sbstrlen = i;
for(i = 0; str[i] != '\0'; i++);
strlen = i;
if(sbstrlen > strlen)
{
printf("\n**Error substring is larger than base string!");
return 2;
}
if(sbstrlen == strlen)
{
if(str == sbstr) return 0;
else return 1;
}
for(i = 0; i <= strlen; i++)
{
if(str[i] == sbstr[p]) p++;
else if(str[i] != str[i - 1]) p = 0;
if(p == sbstrlen) return 0;
}
return 1;
}
Recursion can do this better. Oh, and by the way, descriptive identifiers are way better. There’s no reason to randomly remove all the vowels, and don’t forget
const.