Thread: String split() in C and C++

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    21

    String split() in C and C++

    Hi, this is a cpp file. I was wondering how I could find a way to remove the need for the 3rd parameter of split() -> c function. As of now it is essential as it helps to free up the memory, and any way to improve the cpp split() function? Thanks.

    Code:
    #ifdef __cplusplus
    extern "C" {
    #endif // __cplusplus
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    char** split(char* str, char delim, int* strcount)
    {
        int delimCount = 0, index = 0;
        char new_delim[2], *p_new_d = new_delim;
        *p_new_d = delim;
        *(p_new_d + 1) = '\0';
        for (int i = 0; i < (int)strlen(str); i++)  if (str[i] == delim && str[i + 1] != delim) delimCount++;
        if (delimCount < 1) return NULL;
        char** container = (char**)malloc(sizeof(char*) * ++delimCount);
        char* pos = strtok(str, new_delim);
        while (pos != NULL)
        {
            container[index] = (char*)malloc(sizeof(char) * strlen(pos) + 1);
            strcpy(container[index++], pos);
            pos = strtok(NULL, new_delim);
        }
        *strcount = delimCount;
        return container;
    }
    #ifdef __cplusplus
    }
    #endif // __cplusplus
    
    
    #include <iostream>
    #include <string>
    #include <sstream>
    #include <vector>
    
    
    class StringManip
    {
    private:
        enum class _split : bool { all = true, noEmpty = false };
    public:
        typedef _split splitOption;
    
    
        static std::vector<std::string> split(std::string word, char delim, splitOption split_option)
        {
            std::vector<std::string> splited_data;
            std::stringstream ss(word);
            std::string token;
            while (std::getline(ss, token, delim))
            {
                if (split_option == splitOption::noEmpty) { if (!token.empty()) splited_data.push_back(token); }
                if (split_option == splitOption::all) splited_data.push_back(token);
            }
            return splited_data;
        }
    };
    
    
    int main()
    {
        char str[] = "this/is/really/awesome";
        std::string ss = str;
        int size;
        char** splited = split(str, '/', &size);
        if (splited != NULL)
        {
            for (int i = 0; i < size; i++)
            {
                printf("%s\n", splited[i]);
                free(splited[i]);
            }
            free(splited);
        }
        for (auto& s : StringManip::split(ss, '/', StringManip::splitOption::noEmpty)) std::cout << s << '\n';
    }
    Last edited by flash13; 01-05-2019 at 09:18 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,408
    The other way is to set the last container[index] to NULL.

    So in main, you have
    Code:
    while ( splited[i] != NULL ) {
        // stuff
        i++;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,064
    I suggest that you keep it. Replacing it with Salem's suggestion is an option, but it isn't an improvement as you would basically force the user of the function to iterate over the array to count the number of elements before they can safely use it. Fine if they were going to do that anyway, but inconvenient if they only wanted a specific element.

    I wonder though: you're counting consecutive delimiters as a single delimiter, but your code with strtok does not account for that?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how do i split a string into two?
    By Mohsen Abasi in forum C Programming
    Replies: 2
    Last Post: 04-17-2017, 08:22 AM
  2. Split a string(C)
    By oror84 in forum C Programming
    Replies: 4
    Last Post: 04-11-2011, 11:36 PM
  3. Split String
    By puneetlakhina in forum C Programming
    Replies: 1
    Last Post: 10-06-2008, 02:12 AM
  4. Split a string
    By Tommo in forum C Programming
    Replies: 5
    Last Post: 09-01-2007, 04:53 PM
  5. split string
    By gtr_s15 in forum C++ Programming
    Replies: 2
    Last Post: 12-06-2005, 07:20 AM

Tags for this Thread