This function checks whether or not a substring needle
exists in another string haystack
and returns the position if it does or 0 if it doesn't, unless the position is 0 in which case, it won't be located.
Looking for ways to improve this code, specifically better error handling.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
size_t contains(const char * needle, const char *haystack);
int main(void)
{
char *needle = "test";
char *haystack = "This is a dinosaurtest.";
printf("Position: %lu", contains(needle, haystack));
return EXIT_SUCCESS;
}
size_t contains(const char * needle, const char *haystack)
{
if(needle == NULL || haystack == NULL)
{
return 0;
}
long int first_char_pos = -1;
size_t len_h = strlen(haystack);
size_t len_n = strlen(needle);
size_t i, j;
size_t exist_count = 0;
// Find the first character. If it doesn't exist, we're done.
for(i = 0; i < len_h; i++)
{
if((haystack[i] == needle[0]) && (first_char_pos == -1))
{
first_char_pos = i;
exist_count++;
}
}
if(first_char_pos == -1)
{
return 0;
}
printf("First char match index: %li\n", first_char_pos);
printf("Char: %c\n", haystack[first_char_pos]);
size_t current_index = (size_t) first_char_pos;
for(i = first_char_pos; i < len_h; i++)
{
if(haystack[i] == needle[exist_count] && (i == (current_index + 1)))
{
current_index = i;
exist_count++;
}
printf("Exist count: %lu\n", exist_count); //<--Debugging
if(exist_count == len_n)
{
return first_char_pos;
}
}
return 0;
}
strstr()
. There's a safer version calledstrnstr()
. You can find an implementation here: github.com/lattera/freebsd/blob/master/lib/libc/string/… \$\endgroup\$ – alx Aug 10 '19 at 21:26contains("tt", "test")
return true? \$\endgroup\$ – Roland Illig Aug 11 '19 at 16:21