Skip to content

Instantly share code, notes, and snippets.

@airvzxf
Created February 23, 2023 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airvzxf/9ec67b227dd5db326fd083cf09751ff2 to your computer and use it in GitHub Desktop.
Save airvzxf/9ec67b227dd5db326fd083cf09751ff2 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cstring>
void string_split(const char *text, const char *delimiter, char *tokens[10]);
int main() {
// Convert String into Array of Strings.
// Managing memory is usually a feat.
// Furthermore, execute in terminal: `g++ main.cpp -o strings-c`.
const char *text = "a/apple/arm/basket/bread/car/camp/element/...";
const char *split_char = "/";
char *tokens[10];
string_split(text, split_char, tokens);
std::cout << "\nConvert String into Array of Strings." << std::endl;
for (auto &token: tokens) {
std::cout << "Word: " << token << std::endl;
}
return 0;
}
void string_split(const char *text, const char *delimiter, char *tokens[10]) {
char *token, *str, *toFree;
toFree = str = strdup(text);
int index = 0;
while ((token = strsep(&str, delimiter))) {
std::cout << "token: " << token << std::endl;
tokens[index++] = token;
}
free(toFree);
free(str);
free(token);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment