4 ms·
NAME strstr - locate a substring SYNOPSIS int strstr(string haystack, string needle, int offset); DESCRIPTION The strstr() function finds the first o
by Karellen 13y ago
NAME
strstr - locate a substring
SYNOPSIS
int strstr(string haystack, string needle, int offset);
DESCRIPTION
The strstr() function finds the first occurrence of the substring needle
in the string haystack, starting from position offset in haystack.
RETURN VALUE
This function returns the index of the first character in haystack after
offset where needle can be found, or -1 if the substring is not found (or
if offset is out of bounds for haystack).
Same complexity and memory overhead as C strstr(). Actually more efficient if needle is longer than haystack + offset, which can be checked in O(1) on entry.
(I don't have a problem with NUL-terminated strings, but couldn't resist a little sideways thinking on how an alternate library implementation for strings might work.)
- thedufer 13y agoThat's a far less useful function, since you still have to do a memory copy if you want to pass the return value to a function that operates on strings.
- Karellen 13y agoOr you could just pass 'needle', which is already that string.
- thedufer 13y agoOnly if the first occurrence of needle happens to terminate the string. Otherwise the return value of the real version of strstr returns a string that starts with needle but is followed by more text.
- Karellen 13y agoOK, so for that one particular use case[0], the result of strstr might not be quite as convenient as the NUL-terminated strstr() case. But that's what you get with a completely different string implementation - some operations are more efficient than others, others less so. It's a bunch of trade-offs. But strstr() finds the position of a substring within a larger string, or indicates that it doesn't exist. My suggested API for the equivalent functionality does exactly that, with no problems or performance issues for the job strstr() itself needs to do that I can see. [0] A use case I have to say I find a little contrived. I can say that the majority of the times I've used strstr(), it's either to simply check that needle exists in haystack, or to take the part of the haystack following needle - at which point I normally need to make a copy because I can't guarantee that the source string will be around for the lifetime that I need the remainder for.
- thedufer 13y agoDifferent experiences, I guess. Your "contrived use case" is my "only reason I've ever used strstr". That said, I haven't done a ton of C programming, so maybe my experience is atypical.