题目:编写字符串截断函数char ** StrToK(const char* S1, const char* S2)。
功能:字符串S2对字符串S1进行截断,并分别输出截断的字符串
举例:S1=abcdefg, S2=be,最后返回一个字符串数组,将a,cd,fg三个字符串用指向指针的指针返回。
思路:遇到相等字符或者字符串结束符,则表示每一行字符串结束
陷阱:
(1)函数返回指向指针的指针,不能再函数内部定义静态的而为字符串数组,因为函数结束,其生命期结束。
(2)如果遇到S1 = "abcde",S2 = "bc"时,分割的字符串是a,de。容易出现在a和de之间插入'0'的情况。
代码:
#include <iostream> #include <assert.h> using namespace std; char ** StrToK(const char* S1, const char* S2) { assert(S1 != NULL && S2 != NULL); int nCurS1 = 0; int nCurS2 = 0; int nLenS1 = strlen(S1); int nLenS2 = strlen(S2); int nLastLoc = -1; int nCurRow = 0; int nCurCol = 0; bool bIsCreate = false; char** pArrStr = new char*[nLenS1/2 + 1]; //字符串为空,处理边界 if (nLenS1 == 0) { return pArrStr; } while(nCurS1 < nLenS1 && nCurS2 < nLenS2) { if (S1[nCurS1] == S2[nCurS2]) { if (nCurS1 != nLastLoc + 1) { pArrStr[nCurRow++][nCurCol++] = '\0'; } nLastLoc = nCurS1;//判断是否两个相等的字符是否挨着 nCurCol = 0; //另起一行存储数据 bIsCreate = false; //上一行数据结束 nCurS2++; } else { if (!bIsCreate) { pArrStr[nCurRow] = new char[nCurS1 + 1]; bIsCreate = true; } pArrStr[nCurRow][nCurCol++] = S1[nCurS1]; } nCurS1++; } if (nCurS1 != nLenS1)//S2串结束,S1还有剩余,需要加入数组 { pArrStr[nCurRow] = new char[nCurS1 + 1]; while(nCurS1 < nLenS1) { pArrStr[nCurRow][nCurCol++] = S1[nCurS1++]; } pArrStr[nCurRow++][nCurCol] = '\0'; } else if (bIsCreate) //上一行数据虽结束,但是没加结束符 { pArrStr[nCurRow++][nCurCol] = '\0'; } //输出 for (int i = 0;i < nCurRow;i++) { cout<<pArrStr[i]<<endl; } return pArrStr; } int main() { // char S1[81] = "abcdefg"; // char S2[81] = "be"; //char S1[81] = "a"; //char S2[81] = "be"; // char S1[81] = "ab"; // char S2[81] = "c"; // char S1[81] = ""; // char S2[81] = "be"; char S1[81] = "abcdefg"; char S2[81] = "abcdefg"; StrToK(S1,S2); system("pause"); return 1; }
疑问:不知道返回值有啥用,因为返回的是二维数组,直接根据二维指针是得不出二维数组中一维的总长度以及包含数据的长度的。
哎,就当练习吧。