查找主串中是否还有子串,如果有则返回匹配的第一个位置

题目:

查找主串中是否还有子串,如果有则返回匹配的第一个位置,否则返回-1

 

#include <stdio.h>
#include <string.h>

int Index(char *origine, char *target)
{
	if (origine ==NULL||target == NULL)	//先检查是否为空
	{
		printf("there is a false\n");
		return -1;
	}
	int origStrLen = strlen(origine);
	int targetLen = strlen(target);
	int pos = -1;
	int prePos = pos;
	int i = 0;
	int j = 0;

	while(i < origStrLen && j < targetLen) // i,j都从0开始,故是<而不是<=
	{
		if (origine[i] == target[j])
		{
			++i;
			++j;
		}
		else
		{
			i = i - j + 1;	//i退回到上次匹配首位的下一位
			j = 0;			//每次从头开始从新查找子串
		}	
	}

	if (j == targetLen)		//判断j是否等于targetLen,如果是则可以获取位置
	{
		prePos = pos;
		pos = i - j;		//获取第一个匹配的位置
	}
	return pos+1;			//因为数组从0开始,所以要加1
}

int main()
{
	if(Index("hello aaaaa", "aa"))	//注意这里的调用要和下面的参数要一致
		printf("子串在主串中,并且第一个匹配的字母在主串第%d位置\n",Index("hello aaaaa", "aa"));
	else
		printf("子串不在主串中\n");
    return 0;
}

执行结果:

 

如果调用的是Index("hello aaaaa", "aA"),或其他不匹配的子串,则打印子串不在主串中,这里不演示了。

posted on 2013-10-11 14:34  love so much  阅读(492)  评论(0编辑  收藏  举报

导航