aboutsummaryrefslogtreecommitdiff
path: root/src/string2.c
blob: 2d59897fc2dab293777d1c7f19dc3f86cddda286 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* See LICENSE file for copyright and license details. */

#include <stdlib.h>
#include <string.h>

char **
strsplit(char *str, char delim, int *size)
{
	char **lines = NULL;
	char *s = str;

	int count = 0;

	for (int start = 0, end = 0; ; s++, end++) {
		if (*s == delim || *s == '\0') {
			int _size = end - start;
			lines = realloc(lines, sizeof(char *) * ++count);
			int idx = count - 1;
			if (_size > 1) {
				lines[idx] = calloc(_size + 1, sizeof(char *));
				strncpy(lines[idx], str + start, _size);
			} else {
				lines[idx] = strdup("");
			}
			start = end + 1; /* plus 1 - skip the delim */
		}
		if (*s == '\0') break;
	}

	*size = count;

	return lines;
}