码迷,mamicode.com
首页 > 其他好文 > 详细

寻找两个字符串中最长的公共子串源码(不使用strcmp)

时间:2015-03-29 22:12:34      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:字符串处理 源码 公共子串 c语言

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *com_child(const char *str1, const char *str2);
int main(void)
{
	char str1[] = "abcdefgehi", str2[] = "aacdef**gehicdefgeabcdefgehi", *strtemp = NULL;
	strtemp = com_child(str1,str2);
	printf("%s\n", strtemp);
	free(strtemp);
}
char *com_child(const char *str1, const char *str2)
{
	char *strtemp = NULL;
	int p,q,n,nmax,max,l1,l2,psave;
	l1 = strlen(str1);
	l2 = strlen(str2);
	max = 0;
	psave = 0;
	for (p = 0; p < l1-1; p++)
	{
		n = 0;
		nmax = 0;
		for (q = 0; q < l2-1; q++)
		{
			if (str1[p] == str2[q] && str1[p+1] == str2[q+1])
			{
				n = 2;
				while (str1[p+n] == str2[q+n] && str1[p+n] != '\0')
				{
					n++;
				}
				if (n > nmax)
				{
					nmax = n;
				}
			}
		}
		if (nmax > max)
		{
			psave = p;
			max = nmax;
		}
	}
	strtemp = (char *)malloc(sizeof(char)*(max+1));
	for (q = 0; q < max; q++)
	{
		strtemp[q] = str1[psave+q];
	}
	strtemp[max] = '\0';
	return strtemp;
}

寻找两个字符串中最长的公共子串源码(不使用strcmp)

标签:字符串处理 源码 公共子串 c语言

原文地址:http://blog.csdn.net/u012914709/article/details/44732083

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!