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;
    }
  • 相关阅读:
    ZedGrapy使用实例
    C#分割字符串(包括使用字符串分割)
    从VS2005项目转换为VS2008项目(C#版)
    关于SQL操作的一些经验
    android socket 编程总结
    Excel绘制人口金字塔图
    使用命令让IE全屏显示指定的页面,适用于触摸屏终端机
    毕业这两年
    使用XML数据结合XSLT导出Excel
    XSLT实现XML作为数据源在web页面显示人口金字塔统计图
  • 原文地址:https://www.cnblogs.com/Lunais/p/5965539.html
Copyright © 2011-2022 走看看