【字符串问题】返回一个字符串的指定子串
2013-09-15 11:06:57
模拟C++中的strstr函数,将主串中子串以及以后的字符串全部返回。
注意:
考虑所有可能的测试用例,包括子串存在、不存在,以及子串、主串为空的情况等。
代码(测试暂未发现问题,欢迎交流指正!):
1 #include <iostream> 2 #include <cassert> 3 using namespace std; 4 5 char *MyStrstr(const char* pSrcStr,const char* pSubStr) 6 { 7 assert(pSrcStr != NULL && pSubStr!= NULL); 8 9 if (! *pSubStr ) //对子串为空的情况特别处理,否则在子串为空时返回原串 10 { 11 return NULL; 12 } 13 14 char *pSrcCur = (char *)pSrcStr; 15 char *pSubCur = NULL; 16 char *pSrcTmp = NULL; 17 18 while (*pSrcCur) 19 { 20 pSrcTmp = pSrcCur; 21 pSubCur = (char *)pSubStr; 22 23 while (*pSrcTmp && *pSrcTmp == *pSubCur) 24 { 25 ++pSrcTmp; 26 ++pSubCur; 27 } 28 29 if ( !(*pSubCur) ) //子串的所有字符都测试通过,说明找到子串,返回起始位置即可 30 { 31 return pSrcCur; 32 } 33 34 ++pSrcCur; 35 } 36 37 return NULL; //没有找到,返回NULL 38 } 39 40 typedef char * pCHAR; 41 42 void TestDriver() 43 { 44 pCHAR srcStrArray[] = {"0123456","0123456","yyabcdabjcabceg","abcbcbcabc","abc","",""}; 45 pCHAR subStrArray[] = {"123","45678","abc","hello","","","abc"}; 46 size_t arrayLength = 7; 47 48 pCHAR srcStr; 49 pCHAR subStr; 50 51 pCHAR pSubPos; 52 53 for (size_t index = 0;index < arrayLength;++index) 54 { 55 srcStr = srcStrArray[index]; 56 subStr = subStrArray[index]; 57 pSubPos = MyStrstr(srcStr,subStr); 58 59 cout<<"the source string is : "<<srcStr<<endl; 60 cout<<"the sub string is : "<<subStr<<endl; 61 62 if (pSubPos != NULL) 63 { 64 cout<<"the sub string is : "<<pSubPos<<endl<<endl; 65 } 66 else 67 { 68 cout<<"the sub string is not found!"<<endl<<endl; 69 } 70 } 71 } 72 73 int main() 74 { 75 TestDriver(); 76 return 0; 77 }
测试结果:
the source string is : 0123456 the sub string is : 123 the sub string is : 123456 the source string is : 0123456 the sub string is : 45678 the sub string is not found! the source string is : yyabcdabjcabceg the sub string is : abc the sub string is : abcdabjcabceg the source string is : abcbcbcabc the sub string is : hello the sub string is not found! the source string is : abc the sub string is : the sub string is not found! the source string is : the sub string is : the sub string is not found! the source string is : the sub string is : abc the sub string is not found! 请按任意键继续. . .