从源字符串截取子串相关函数的封装

来源:互联网 发布:淘宝店铺页头图片大小 编辑:程序博客网 时间:2024/05/21 06:41

一、从源字符串中截取左右两个子串之间的字符串。

例如,源字符串:123defabc456def789,截取abc(左)与def(右)两个子字符串之间的字符串:结果应该为456。

函数的实现封装如下:

//获取左右两个字符串之间的字符串CString GetMidStrByLAndR(CString& strSrc, CString strLeft, CString strRight){CString strRet;int eIdxBegin = strSrc.Find(strLeft);if(eIdxBegin != -1)//找到了左串{eIdxBegin += strLeft.GetLength();//左串最后一个字符在strSrc的位置d1int eIdxEnd = strSrc.Find(strRight, eIdxBegin);//找到右串第一个字符在strSrc的位置d2if (eIdxEnd != -1){strRet = strSrc.Mid(eIdxBegin, eIdxEnd-eIdxBegin);//截取位置d1和d2之间的字符串return strRet;}}return strRet;}


二、以特殊的标志字符对字符串进行截取。

例如,源字符串:123#456#789#abc#def,以#号为标志字符,对字符串进行截取操作。

函数实现封装如下:

//拆解格式化字符串有用信息int getcmdstr(char *pinstr,char *poutstr,int num){int i;int j;int ilast;int inext;int ilen=strlen(pinstr);int a;/*   TFDSYY#FR#22#297edff859c3aa36015a971faff13c4f#    */if(num==1)//获取设备类型{for(i=0;i<ilen;i++)if(*(pinstr+i)=='#')break;for(j=0;j<i;j++)*(poutstr+j)=*(pinstr+j);*(poutstr+j)='\0';return 1;}for(ilast=0,a=0;ilast<ilen;ilast++)if(*(pinstr+ilast)=='#'){a++;if(a==(num-1))break;}for(inext=ilast+1;inext<ilen;inext++)if(*(pinstr+inext)=='#')break;for(j=ilast+1,i=0;j<inext;j++,i++)//ilast与inext是定位两个#之间*(poutstr+i)=*(pinstr+j);*(poutstr+i)='\0';return 1;}

其中:第一个参数为源串,第二个参数为截取后的子字符串,最后一个参数为截取哪一部分。

例如,我们要去子字符串456,只需将第三个参数赋值为2.

0 0
原创粉丝点击