C++ strpos function


Here is a continuation of the implentation of the php api with stl strings. In this case we are looking at strpos. It returns the position of one string in the other. If not found it returns string::npos which is of type size_t. For those who aren't used to seeing size_t, it is basically an integer, except that the max integer value is defined as string::npos.

If the 'needle' parameter is not found in the php strpos returns 'false', which has to be differentiated from a string found at position 0 (which return 0 and 0 can evaluate to false). This is why we use string::npos as our 'false' instead of 0. In the STL string::npos is a null position (string.find() returns string::npos in some cases).
#include <iostream>
#include <string>
#include <vector>
 
using namespace std;
 
size_t strpos(const string &haystack, const string &needle);
 
int main(int argc, char *argv[])
{
    string haystack="012345";
 
    cout << " 0:"<< strpos(haystack, "0") << endl;
    cout << " 1:"<< strpos(haystack, "1") << endl;
    cout << " 5:"<< strpos(haystack, "5") << endl;
    cout << " 6:"<< strpos(haystack, "6") << endl;
    cout << "01:"<< strpos(haystack, "01") << endl;
    cout << "45:"<< strpos(haystack, "45") << endl;
    cout << "56:"<< strpos(haystack, "56") << endl;
 
    return 0;
}
 
size_t strpos(const string &haystack, const string &needle)
{
    int sleng = haystack.length();
    int nleng = needle.length();
 
    if (sleng==0 || nleng==0)
        return string::npos;
 
    for(int i=0, j=0; i<sleng; j=0, i++ )
    {
        while (i+j<sleng && j<nleng && haystack[i+j]==needle[j])
            j++;
        if (j==nleng)
            return i;
    }
    return string::npos;
}

code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)