I'm writing a function to split a string into a pointer to pointer, If separator is space, I want to split only the words that are not inside quotes. e.g Hello world "not split"
should return
Hello
world
"not split"
somehow the function split the words inside the quotes and doesn't split words outside the quotes.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int is_quotes(char *s)
{
int i;
int count;
i = 0;
count = 0;
while (s[i])
{
if (s[i] == '"')
count++;
i++;
}
if (count == 0)
count = 1;
return (count % 2);
}
int count_words(char *s, char sep)
{
int check;
int i;
int count;
check = 0;
if (sep == ' ')
check = 1;
i = 0;
count = 0;
while (*s && *s == sep)
++s;
if (*s)
count = 1;
while (s[i])
{
if (s[i] == sep)
{
if (!is_quotes(s + i) && check)
{
i += 2;
while (s[i] != 34 && s[i])
i++;
}
count++;
}
i++;
}
return (count);
}
char *ft_strsub(char const *s, unsigned int start, size_t len)
{
char *sub;
sub = malloc(len + 1);
if (sub)
memcpy(sub, s + start, len);
return (sub);
}
char **ft_strsplit(char const *s, char c)
{
int words;
char *start;
char **result;
int i;
words = count_words((char *)s, c);
if (!s || !c || words == 0)
return (NULL);
i = 0;
result = (char **)malloc(sizeof(char *) * (words + 1));
start = (char *)s;
while (s[i])
{
if (s[i] == c)
{
if (is_quotes((char *)s + i) == 0 && c == ' ')
{
i += 2;
while (s[i] != '"' && s[i])
i++;
i -= 1;
}
if (start != (s + i))
*(result++) = ft_strsub(start, 0, (s + i) - start);
start = (char *)(s + i) + 1;
}
++i;
}
if (start != (s + i))
*(result++) = ft_strsub(start, 0, (s + i) - start);
*result = NULL;
return (result - words);
}
int main(int argc, char **argv)
{
if (argc > 1)
{
char **s;
s = ft_strsplit(argv[1], ' ');
int i = 0;
while (s[i])
printf("%s\n", s[i++]);
}
return 0;
}
When I run this code with hello world "hello hello"
I get the following
hello world
"hello
hello"