Reputation: 71
I have an exercise where I should implement the strstr
function from the standard library. The implementation of strstr
seems to work, however, while it points to 'B', from "Foo Bar Baz", it returns "Bar Baz". How could I change the returned subscript so that it only returns the first occurrence of "B" of "Bar" in "Foo Bar Baz"?
From the manual:
If needle is an empty string, haystack is returned; if needle occurs nowhere in haystack, NULL is returned; otherwise a pointer to the first character of the first occurrence of needle is returned.
#include <stdio.h>
char *ft_strstr(char *str, char *to_find)
{
int i;
int n;
i = 0;
n = 0;
if (to_find == NULL || str == NULL)
return str;
if (to_find != NULL)
{
while (str[i] != '\0' && to_find[n] != '\0')
{
while (str[i] == to_find[n])
{
i++;
n++;
}
i++;
}
return str[i - n - 1];
}
else
return NULL;
}
int main() {
char *largestring = "Foo Bar Baz";
char *smallstring = "Bar";
char *ptr;
ptr = ft_strstr(largestring, smallstring);
printf("%s", *ptr);
return 0;
}
Upvotes: 0
Views: 612
Reputation: 31409
You're trying to mimic the standard strstr
function, but that function does not do what you're asking for. It actually does return a pointer to the first occurrence of str
in to_find
. Your current approach is actually correct.
However, there is two bugs. One is this line in ft_strstr
:
return str[i - n - 1];
that should be:
return &str[i - n - 1];
The other one is in main
:
printf("%s", *ptr);
that should be
printf("%s", ptr);
Fix these two things and your code should work as it should.
If needle is an empty string, haystack is returned; if needle occurs nowhere in haystack, NULL is returned; otherwise a pointer to the first character of the first occurrence of needle is returned.
The pointer will still always (unless it's a null pointer) point somewhere in the haystack. I think that's what's confusing you.
Maybe this code snippet will help you:
char *largestring = "Foo Bar Baz";
char *smallstring = "Bar";
char *ptr = strstr(largestring, smallstring);
int index = ptr - largestring;
The variable index
will now contain the index of the first occurrence, in your case it will be 4. (Given that it was found. It's possibly undefined behavior otherwise.)
Upvotes: 0
Reputation: 34585
The difference in what you report is not what is returned, but what you do with it. But first you have some errors:
return str[i - n - 1];
should be return &str[i - n - 1];
printf("%s", *ptr);
should be printf("%s", ptr);
NULL
, you
should explicity return NULL
for failure, otherwise the caller will think a substring was found.NULL
(not found) before you
dereference it.You can print the result, and, just the first character with
printf("%s\n", ptr);
printf("%c\n", *ptr);
Upvotes: 1