查找两个字符串中的最大公共字串

使用C语言,编写函数,查找两个字符串中最大公共字串,如:字符串A="abcdefg",字符串B="cdeab",做大公共字串为“cde”。

思路:先确定短的字符串short_str和长的字符串long_str,用short_str在long_str中匹配,如果没匹配到,将short_str最后一个字符置'\0',再去匹配,直到匹配到了返回字符串指针。

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

char* get_common_str(char *pStr1, char *pStr2)
{
    if ((pStr1 == NULL) || (pStr2 == NULL)) {
        return NULL;
    }

    char* pShortStr = NULL, *pLongStr = NULL;
    if (strlen(pStr1) < strlen(pStr2)) {
        pShortStr = pStr1;
        pLongStr = pStr2;
    } else {
        pShortStr = pStr2;
        pLongStr = pStr1;
    }

    if (strstr(pLongStr, pShortStr) != NULL) {
        return pShortStr;
    } else {
        for (int i = strlen(pShortStr) - 1; i >= 0; --i) {
            pShortStr[i] = '\0';
            if (strstr(pLongStr, pShortStr) != NULL) {
                return pShortStr;
            }
        }
    }

    return NULL;
}

int main()
{
    //最大字串:cde
    char szBuf1[32] = { 0 };
    strcpy(szBuf1, "abcdefg");
    char szBuf2[32] = { 0 };
    strcpy(szBuf2, "cdeab");

    char* pResult = get_common_str(szBuf1, szBuf2);
    printf("pResult=[%s]\n", pResult);
    return 0;
}

程序运行结果如下:

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值