实现朴素的字符串匹配

实现函数int FindSubStr(char* t, char* p)。
相关知识
在一个长字符串中寻找一个短字符串出现的位置,这是字符串匹配问题。
例如:长字符串是 “string” ,短字符串是 “ring” ,那么短字符串在长字符串中出现的位置是 2 ,即 “ring” 在 “string” 中出现的开始位置是 2 。

#include <stdio.h>
#include <stdlib.h>
#include "mystr.h"
#pragma warning(disable:4996)
int FindSubStr(char* t, char* p)
{
    int i=0, j=0;
    while(p[i]!=0 && t[j]!=0) 
    {
        if (p[i]==t[j]) 
 	{
            i ++;
            j ++;
        }
        else
	{
            j = j-i+1;
            i = 0;
        }
    }
    if (p[i] == 0)
    {
	return j-i;
    }
    else 
    {
         return -1;
    }
}
int main()
{
 // to test finding the first son string	
	char t[100]; // mother string
 	char p[100]; // son string
 	scanf("%s", t);
 	scanf("%s", p);
 	int i=FindSubStr(t, p);
 	printf("Location: ");
 	if(i==-1) 
 	{
 		 printf("not found!");
 	}
 	else 
 	{
 		 printf("%d",i); 
	 }
    	 return 0;
}
发布了180 篇原创文章 · 获赞 169 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/huangziguang/article/details/105523400