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';
}