国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > 在字符串中找到全部是由指定的字符组成的最长子串

在字符串中找到全部是由指定的字符组成的最长子串

来源:程序员人生   发布时间:2015-05-11 08:31:21 阅读次数:3286次
/* *!============================================================== *! FNAME: search.cpp *! BRIEF: *! AUTHR: RollStone *! EMAIL: jealdean@outlook.com *! VERNO: 1.0.31 *! CREAT: 2015-04⑵8 23:43:04 *! CHGON: 2015-04⑶0 07:53:00 *! *! Copyright (c) 2015 All Rights Reserved By Abodu Org *!============================================================== */ ///编写1个 C 函数,该函数在1个字符串中找到可能的最长的全部是由指定的字符组成的子字符串 #include <stdio.h> #include <string.h> #include <stdlib.h> #ifndef strndup //自己手动实现 复制字符串前 n 个字符 char* strndup(const char* src,int nMax) { int srcLen=strlen(src); int n=(srcLen<nMax)?srcLen:nMax; char* dest=(char*)calloc(n+1,sizeof(char)); while(--n>=0) dest[n]=src[n]; return dest; } #endif /** * @brief * 在1个字符串中找到可能的最长的子字符串(该子字符串由同1字符组成) * @param str[] * @param tc 目标字符 * @param rcLen 返回的目标子串的长度 * * @return * tc没有在str中出现,返回NULL,否则返回最长子串的起始位置 */ char* search_max_substr(char src[],char ch,int* rcLen) { char* pStart; if(!src||!(pStart=strchr(src,ch))) { return NULL; } *rcLen=1;//最少有1个 char* pEnd=strrchr(src,ch); if(pEnd==pStart) { //有且唯一唯1的1个字符ch return pStart; } char* rcOut=pStart; char* pCur=pStart+1; while(pCur-1<=pEnd) { if( *(pCur-1)==*pCur) { pCur++; continue; } //当前指针与其紧邻的前1个指针的内容不相同 if(pCur-pStart>*rcLen) { //找到个数大于rcLen rcOut=pStart; *rcLen=pCur-pStart; //记录旧的移动次数 } //找到剩下的字符串内的第1个ch if(!pCur||!(pStart=strchr(pCur,ch))) { break; } pCur=pStart+1; } return rcOut; } int main ( int argc, char* argv[] ) { char s[]="AAAABBBCCDDEFFFFFFFFFF"; int n=0; char* p=search_max_substr(s,'D',&n); if(p) { char* sbk=strndup(p,n); if(sbk) { printf("RESULT:%s ",sbk); free(sbk); } } return 0; } // end main
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生