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;
}

原文链接: https://www.cnblogs.com/Lunais/p/5965539.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/242188

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午10:10
下一篇 2023年2月13日 下午10:10

相关推荐