Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "cstdio"
- #include <cstring>
- #include <cstdlib>
- char **split(const char *str, const char *delim)
- {
- char **res = (char**)malloc(strlen(str) * sizeof(char*));
- if (!res)
- return NULL;
- for (int i = 0; i < (int)strlen(str); i++)
- {
- res[i] = NULL;
- }
- int n = 0, dl = strlen(delim);
- const char *s = str;
- const char *cd = delim;
- for (; *str; ++str)
- {
- if (*str == *cd)
- {
- cd++;
- if (!*cd)
- {
- res[n] = (char*)malloc(str - s - dl + 2);
- memcpy(res[n], s, str - s - dl + 1);
- res[n][str - s - dl + 1] = 0;
- s = str + 1;
- cd = delim;
- n++;
- }
- }
- else
- {
- cd = delim;
- }
- }
- res[n] = (char *)malloc(str - s + 1);
- strcpy(res[n], s);
- return res;
- }
- void clear(char**res)
- {
- for (int i = 0; res[i]; i++)
- {
- free(res[i]);
- }
- free(res);
- }
- int main()
- {
- char str[] = "abracadabra";
- char delim[] = "br";
- char **res = split(str, delim);
- for (int i = 0; res[i]; i++)
- {
- printf("%s\n", res[i]);
- }
- clear(res);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement