All pastes #47076 Raw Edit

Something

public text v1 · immutable
#47076 ·published 2006-03-26 21:22 UTC
rendered paste body
#include <stdio.h>
#include <string.h>

#include <new>

using namespace std;

int scount_chars(char *str, char c) {
    int i;
    int num_chars = 0;
    for (i = 0; i < strlen(str); i++) {
	num_chars += (str[i] == c) ? 1 : 0;
    }

    return num_chars;
}

int strnsplit(char *str, char c, int n, char ***dest) {
    int i = 0;
    char *token;
    char delim[2];
    /* make a copy, because strtok modifies the original */
    char *str2 = strdup(str);
    /* strtok takes a string as a delimiter */
    delim[0] = c;
    delim[1] = '\0';

    int nc = scount_chars(str, c);
    n = (n > nc) ? nc : n;

    if (*dest) {
        delete [] *dest;
    }
    try {
        *dest = new char*[n+1];
    }
    catch (std::bad_alloc) {
        *dest = 0;
    }
    for (token = strtok(str2, delim); token; token = strtok(NULL, delim)) {
        *dest[i] = strdup(token);
        i++;
    }
    return i;
}

int main() {
	/* will want to strip the ';' before running split */
	char foo[50] = "abcdabcd,efgh,ijkl,mnop";
	char **bar = 0;
	strnsplit(foo, ',', 4, &bar);

	int i;
	for (i=0; i<4; i++) {
		printf("%s\n", bar[i]);
	}

	return 0;
}