string::find 的简单实现

int strStr(string haystack, string needle) {
    if (needle.empty()){
        return 0;
    }
    
    if (haystack.length() < needle.length()){
        return -1;
    }
    
    if (haystack.length() == needle.length()){
        return haystack == needle? 0 : -1;
    }
    
    auto it = haystack.cbegin();
    auto it2 = needle.cbegin();
    auto check = [&]
    {
        auto tempIt = it;
        it2 = needle.cbegin();
        while (it2 != needle.cend()){
            if (*tempIt != *it2){
                return false;
            }
            ++tempIt;
            ++it2;
        }
        return true;
    };
    
    auto const end = haystack.cend() - needle.length() + 1;
    while (it != end){
        if (check()){
            return static_cast<int>(it - haystack.cbegin());
        }
        ++it;
    }
    return -1;
}

 

posted @ 2015-08-24 03:07  wu_overflow  阅读(367)  评论(0编辑  收藏  举报