char *strstr(const char *haystack, const char *needle);
The str function strstr finds the first occurence of needle in haystack. Trailing nulls are not used.

Returns NULL, or the pointer to the trailing substring.

I just love those parameter names. What operating system other than linux would let you find a needle in a haystack natively?

Seriously though, this is a very useful function. Great for finding things, of course, and the "trailing substring as return value" feature is really useful. Want to count all the occurences of a substring?

int findSubStr(const char *haystack, const char *needle) {
     char * foo;

     if(foo=strstr(haystack, needle)) {
           return 1 + findSubStr(foo, needle); //Return 1
                        // we got a match
                        // plus all 1's returned 
                        // from searches of remnants...

     return 0; //Return 0 - no match.
This sucker will recursively count them, going down the list. Note that some early versions of linux bletch on null arguments, so this code needs a bit more error checking. An excellent exercise for the reader, don'tcha think?

NOTE ON TRAILING SUBSTRINGS: The "trailing substring" which strstr points to in its return value is actually cleverness. It does not allocate a new string - it simply returns a pointer pointing to the character immediately after the last character in the delimeter delim. This gives the effect of returning a pointer to some new string, but this is not the case. Be very careful about when you free things with this function!

Log in or registerto write something here or to contact authors.