C语言实现的split

  • Post author:
  • Post category:其他


#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <malloc.h>

int split(char **strOut, char *strIn, char* separator){
    
    int counter = 0;
    char *buffer = NULL;

    if (strIn == NULL)
    {
        return counter;
    }

    int len = strlen(strIn);
    
    while (NULL != strIn)
    {
        char *p = strsep(&strIn, separator);
        if ((NULL != p) && (len != strlen(p)) && (strlen(p) > 0))
        {
            buffer = (char *)malloc(strlen(p) + 1);
            memset(buffer, 0, sizeof(p));
            strcpy(buffer, p);
            strOut[counter] = buffer;
            counter++;
        }
    }
   
    return counter;
}

void myfree(char **ppArray, int counter){
    for(int i = 0; i < counter; i++){
        printf("%p[%d] = %s\n", ppArray[i], i, ppArray[i]);
        free(ppArray[i]);
    }
}

int main(int argc, char **argv){

    char *start = strdup("192.168.1.1,192.168.1.2,192.168.1.3");
    char *buffer = start;
    char *septor = ",";

    char **splitRes;

    int counter = split(splitRes, start, septor);

    printf("counter = %d\n", counter);

    for (int i = 0; i < counter; i++)
    {
        printf("%p[%d] = %s\n", splitRes[i], i, splitRes[i]);
    }
    
    free(start);
    myfree(splitRes, counter);
    
    
    return true;
}



版权声明:本文为oria2006原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。