20分钟不到写的求两个字符串最大公共字串的小程序,欢迎大家指正不足之处。
假如我20分钟不到就写出来这样的程序,算什么样的水平呢?
#include <stdio.h>#include <string.h>#include <malloc.h>#define INVALID_PARA -1#define FAIL 1#define SUCCESS 0#define NOT_FOUND 2typedef unsigned long ulong;ulong get_common_string(char* pStr1, char* pStr2, char** pResult);int main(){ char str1[] = "abcdefg"; char str2[] = "hbcdefgh"; char* pstr = (char*)malloc(10); memset(pstr,0,10); if (SUCCESS == get_common_string(str1, str2, &pstr)) { printf(pstr); } free(pstr); return 0;}ulong get_common_string(char* pStr1, char* pStr2, char** pResult){ ulong match_count_max = 0; ulong match_count = 0; ulong val = 0; ulong pos = 0; char* pcTemp1 = NULL; char* pcTemp2 = NULL; if ((NULL == pStr1) || (NULL == pStr2) || (NULL == pResult)) { return INVALID_PARA; } pcTemp1 = pStr1; pcTemp2 = pStr2; while ('\0' != *pStr1) { while('\0' != *pStr2) { while((pStr1[val]==pStr2[val]) && ('\0' != pStr1[val]) && ('\0' != *pStr2)) { match_count++; val++; } if(match_count > match_count_max) { match_count_max = match_count; pos = strlen(pcTemp1) - strlen(pStr1); } pStr2++; } val = 0; match_count = 0; pStr1++; pStr2 = pcTemp2; } if (0 == match_count_max) { return NOT_FOUND; } else { strncpy(*pResult, pcTemp1 + pos, match_count_max); return SUCCESS; }}