字串的分割

#include <iostream>
using namespace std;

//字串分割函式,不需要改,直接使用,使用方式請看主程式main
char** str_split( char* str, char delim, int* numSplits ) 
{
    char** ret;
    int retLen;
    char* c;

    if ( ( str == NULL ) ||
        ( delim == '\0' ) )
    {
        /* Either of those will cause problems */
        ret = NULL;
        retLen = -1;
    }
    else
    {
        retLen = 0;
        c = str;

        /* Pre-calculate number of elements */
        do
        {
            if ( *c == delim )
            {
                retLen++;
            }

            c++;
        } while ( *c != '\0' );

        ret = (char **)malloc( ( retLen + 1 ) * sizeof( *ret ) );
        ret[retLen] = NULL;

        c = str;
        retLen = 1;
        ret[0] = str;

        do
        {
            if ( *c == delim )
            {
                ret[retLen++] = &c[1];
                *c = '\0';
            }

            c++;
        } while ( *c != '\0' );
    }

    if ( numSplits != NULL )
    {
        *numSplits = retLen;
    }

    return ret;
}

void main()
{
    char* str = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC"; //要分割的字串

    char* strCpy; //複製的字串指標
    char** split; //分割出來的子字串陣列
    int num; //分割出來的子字串數量
    int i;

    strCpy = (char *)malloc( strlen( str ) * sizeof( *strCpy ) ); //配置記憶體空間,來複製str字串
    strcpy( strCpy, str ); //複製字串str至strCpy

    split = str_split( strCpy, ',', &num );
    //呼叫str_split函式,將strCpy字串以逗點分割,傳出分割好的子字串陣列

    if ( split == NULL ) //如果字子字串陣列為空值(NULL)
    {       
        cout << "字串分割傳回空值" ;
    }
    else
    {
        cout << num << "個結果:" << endl;

        for ( i = 0; i < num; i++ )
        {
            cout <<  split[i] << endl; // 輸出每一個子字串陣列的字串
        }
    }
    system("pause");
}

results matching ""

    No results matching ""