zoukankan      html  css  js  c++  java
  • 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 != '')
       {
           while(*end != '' && *end != aSeperator && *end != '(')
           {
               ++end;
           }//end while
    
           // '('和')'配对
    
           if(!isCprocessing && '(' == *start)
           {
               ++end;
               while(*end != '' && *end != ')')
               {
                   ++end;
               }
               if('' == *end)
                   end = start + 1;
    
           }
    
           if('(' == *start)
               isCprocessing = true;
    
           if('(' == *end)
           {
               const char* temp = end++;    //先保存这个位置,在括号不配对时,记得将end置位
               while(*end != '' &&  *end != ')')
               {
                   ++end;
               }//end while
               if('' == *end)
                   end = temp;
           }
    
           if('' == *end)             //none aSeperator
           {
               cout << start << endl;
               break;
           }
    
           //剩下最后一种,遇到分隔符,此时统计分隔符的个数
           char* tem = new char[len + 1];
           char* temStart = tem;
    
            while(aSeperator == *end )
            {
                *tem++ = *end++;     //end指向分隔符的下一项
            }
            *tem = '';
            if(strlen(temStart) == 1)
            {
                while(start != end - 1 && *start != '')
                    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;
    }
  • 相关阅读:
    hdu2049.java
    java输入输出流小细节
    滚动字幕
    hdu4504java
    HDU2054JAVA
    hdu2058java
    hdu2073递推题
    [转]SELinux管理与配置
    Can't connect to MySQL server on 'XXX' (13)
    CentOS6.5+php5.3听云安装过程
  • 原文地址:https://www.cnblogs.com/Lunais/p/5965539.html
Copyright © 2011-2022 走看看