http://top-e.org/jiaoshi/html/?522.html “顶嵌杯”决赛第1题公布 |
北京顶嵌嵌入式培训机构 2010-02-01 10:10:02 作者:“顶嵌杯”工作组 来源:“顶嵌杯”工作组 文字大小:[大][中][小] |
题目名称:根据关键字进行字符串拷贝 Description 把源字符串拷贝到目的字符串,如果指定关键字,则以该关键字结束(不包括关键字本身),如果拷贝失败,则得到空串。 int SafeStrcpy2KeyWord(char* pDestBuffer, //拷贝的目的地地址 char* pSourceString, //拷贝的源地址 int nDestBufferSize, //拷贝的目的地缓冲区长度 char* szKeyWord); //指定关键字符串 返回值:所拷贝的字符串长度。如果拷贝失败,则返回0。 Input 输入包含多组数据,以EOF结束 Output 对于每组数据输出拷贝的长度和拷贝后的目的字符串,以空格分隔。如果该目的字符串为空,则用”NULL”表示。 Sample Input /home/tony/work_server/1/rtest/relayer.out / /t /1/r . NULL END Sample Output 0 NULL 5 /home 22 /home/tony/work_server 38 /home/tony/work_server/1/rtest/relayer 0 NULL Source (参考代码) #include<stdio.h> #include<string.h>
#define MAX_TEXT_LEN 258 #define MAX_PAT_LEN 18
int KMPSingleMatch(char* pText,char* pPat) { int patlen = 0,textlen = 0,i = 0,k = 0; int prefix[MAX_PAT_LEN] = { 0 }; if(NULL == pText || NULL == pPat) return 0; patlen = strlen(pPat); if(0 == patlen) return 0; for(i = 1;i < patlen;++i) { for(;k > 0 && pPat[k] != pPat[i];k = prefix[k-1]); if(pPat[k] == pPat[i]) ++k; prefix[i] = prefix[k-1]; if(0 == k || i + 1 == patlen || pPat[k] != pPat[i+1]) prefix[i] = k; } textlen = strlen(pText); for(i = 0,k = 0;i < textlen;++i) { for(;k > 0 && pPat[k] != pText[i];k = prefix[k-1]); if(pPat[k] == pText[i]) ++ k; if(k == patlen) return i - patlen + 1; } return -1; }
int SafeStrcpy2KeyWord(char* pDestBuffer,char* pSourceString,int nDestBufferSize,char* szKeyWord) { int pos = 0,srclen = 0,i = 0; if(NULL == pDestBuffer) return 0; if(NULL == szKeyWord || NULL == pSourceString) { *pDestBuffer = 0;return 0; } srclen = strlen(pSourceString); pos = KMPSingleMatch(pSourceString,szKeyWord); if(-1 != pos) srclen = pos; if(srclen >= nDestBufferSize) { *pDestBuffer = 0;return 0; } pDestBuffer[srclen] = 0; if(pDestBuffer == pSourceString) return srclen; if(pSourceString > pDestBuffer) { for(i = 0;i < srclen;++i) *pDestBuffer++ = *pSourceString++; } else { pDestBuffer += srclen - 1;pSourceString += srclen - 1; for(i = 0;i < srclen;++i) *pDestBuffer-- = *pSourceString--; } return srclen; }
int main() { char source[MAX_TEXT_LEN],keystr[MAX_PAT_LEN],dest[MAX_TEXT_LEN]; int res = 0; while(EOF != scanf("%s",source)) { getchar(); while(1) { gets(keystr); if(0 == strcmp(keystr,"END")) break; if(0 == strcmp(keystr,"NULL")) keystr[0] = 0; res = SafeStrcpy2KeyWord(dest,source,MAX_TEXT_LEN,keystr); if(0 == res) printf("0 NULL/n"); else printf("%d %s/n",res,dest); } } return 0; } 注:该代码来自参赛选手北京瑞星研发工程师曾剑杰,被“顶嵌杯”专家评审组公认为符合工程化的高质量代码 |