查找字符串(C++实现)

时间:2022-07-01 06:21:26

查找字符串(C++实现),不使用库函数:

// SubString.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

bool FindSubString(char* srcStr,char* subStr)
{
    char* p = srcStr;
    char* q = subStr;
    if(p ==NULL || *p== '\0')
        return false;
    while(p != NULL)
    {
        //subStr 循环比较结束
        if(*q == '\0')
            return true;
        //srcStr 比 subStr 长度短
        if(*p =='\0')
            return false;
        if(*p != *q)
        {
            p ++;
            q = subStr;
        }
        else
        {
            p ++;
            q ++;
        }
    }
    return false;
}
int _tmain(int argc, _TCHAR* argv[])
{
    char  srcStr[] = "Kobe Bean Bryant, nicknamed the '小飞侠', is an American professional basketball player for the Los Angeles Lakers of the National Basketball Association";
    char subStr[] = "Bryant";
    if(FindSubString(srcStr,subStr))
        cout <<"I find substring" <<endl;
    else
        cout <<"I do not find substring" << endl;
    cin.get();
    return 0;
}