-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsplit_string.c
66 lines (61 loc) · 1.12 KB
/
split_string.c
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "holberton.h"
/**
* splitString - splits string into an array of strings
* separated by spaces
* @build: input build
* Return: true if able to split, false if not
*/
_Bool splitString(config *build)
{
register unsigned int i = 0;
char *tok, *cpy;
if (countWords(build->buffer) == 0)
{
build->args = NULL;
free(build->buffer);
return (false);
}
build->args = malloc((countWords(build->buffer) + 1) * sizeof(char *));
cpy = _strdup(build->buffer);
tok = _strtok(cpy, " ");
while (tok)
{
build->args[i] = _strdup(tok);
tok = _strtok(NULL, " ");
i++;
}
build->args[i] = NULL;
free(cpy);
return (true);
}
/**
* countWords - count number of words in a string
* @str: input string
* Return: number of words
*/
unsigned int countWords(char *str)
{
register int words = 0;
_Bool wordOn = false;
while (*str)
{
if (isSpace(*str) && wordOn)
wordOn = false;
else if (!isSpace(*str) && !wordOn)
{
wordOn = true;
words++;
}
str++;
}
return (words);
}
/**
* isSpace - determines if char is a space
* @c: input char
* Return: true or false
*/
_Bool isSpace(char c)
{
return (c == ' ');
}