首页 > 代码库 > split函数的实现

split函数的实现

split作为字符串分割函数非常有用,但在C++里面没有这个函数。自己实现一个分割函数:

1、遇到多个分隔符连在一起,则不做分割

2、()内的分隔符不起作用

3、如果只有(,没有)不影响分隔符

#include <iostream>#include <cstring>using namespace std;void splitString(const char* aString, char aSeperator){   if(NULL == aString)       return;   const char* start = aString;   const char* end = aString;   int len = strlen(aString);   bool isCprocessing = false;   while(*start != \0)   {       while(*end != \0 && *end != aSeperator && *end != ()       {           ++end;       }//end while       // ‘(‘和‘)‘配对       if(!isCprocessing && ( == *start)       {           ++end;           while(*end != \0 && *end != ))           {               ++end;           }           if(\0 == *end)               end = start + 1;       }       if(( == *start)           isCprocessing = true;       if(( == *end)       {           const char* temp = end++;    //先保存这个位置,在括号不配对时,记得将end置位           while(*end != \0 &&  *end != ))           {               ++end;           }//end while           if(\0 == *end)               end = temp;       }       if(\0 == *end)             //none aSeperator       {           cout << start << endl;           break;       }       //剩下最后一种,遇到分隔符,此时统计分隔符的个数       char* tem = new char[len + 1];       char* temStart = tem;        while(aSeperator == *end )        {            *tem++ = *end++;     //end指向分隔符的下一项        }        *tem = \0;        if(strlen(temStart) == 1)        {            while(start != end - 1 && *start != \0)                cout << *start++;            cout << endl;            start = end;            delete tem;        }        else        {            delete tem;        }   }//end while}int main(){    char str[100];    memset(str, 0 , 100);    cout << "please input str: " << endl;    cin >> str;    char ch = +;    splitString(str, ch);    cout << "Hello World!" << endl;    return 0;}

 

split函数的实现