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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值