add: split_quoted

This commit is contained in:
starnakin 2023-06-29 01:27:17 +02:00
parent a9cf6c2afe
commit a4838cc0b4
3 changed files with 82 additions and 3 deletions

View File

@ -1,10 +1,10 @@
#include "utils.h" #include "utils.h"
int is_in_quote(const char *str) int is_in_quote(const char *str, size_t pos)
{ {
int out = 0; int out = 0;
for (size_t i = 0; str[i] != '\0'; i++) for (size_t i = 0; str[i] != '\0' && i < pos; i++)
{ {
if (str[i] == '\"') if (str[i] == '\"')
{ {

78
src/utils/split_quoted.c Normal file
View File

@ -0,0 +1,78 @@
#include "utils.h"
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
static size_t get_len(const char *str, const char* charset)
{
size_t len = 0;
size_t i = 0;
while (str[i] != '\0')
{
while (str[i] != '\0' && (is_in_quote(str, i) || strchr(charset, str[i]) != NULL))
i++;
if (str[i] == '\0')
return len;
len++;
while (str[i] != '\0' && (is_in_quote(str, i) || strchr(charset, str[i]) == NULL))
i++;
}
return (len);
}
void free_tab(char **tab)
{
for (size_t i = 0; tab[i] != NULL; i++)
free(tab[i]);
free(tab);
}
int fill_tab(char **tab, const char* str, const char* charset)
{
const char *start;
size_t len = 0;
size_t i = 0;
while (str[i] != '\0')
{
while (str[i] != '\0' && (is_in_quote(str, i) || strchr(charset, str[i]) != NULL))
i++;
if (str[i] == '\0')
return len;
start = str + i;
while (str[i] != '\0' && (is_in_quote(str, i) || strchr(charset, str[i]) == NULL))
i++;
tab[len] = strndup(start, (str + i) - start);
if (tab[len] == NULL)
{
free_tab(tab);
return 1;
}
len++;
}
}
char **split_quoted_charset(const char *str, const char *charset)
{
size_t len = get_len(str, charset);
char **tab = malloc((len + 1) * sizeof(char *));
if (tab == NULL)
return NULL;
tab[len] = NULL;
if (fill_tab(tab, str, charset))
return NULL;
return (tab);
}
int main(int ac, char** av)
{
size_t i = 0;
char** tab;
if (ac != 2)
return 1;
tab = split_quoted_charset(av[1], " \t");
while ( tab[i] ) printf( "%s\n", tab[i++] );
free_tab(tab);
}

View File

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <stddef.h> #include <stddef.h>
#include <string.h>
int is_in_quote(const char *str); int is_in_quote(const char *str, size_t pos);