Witam :) potrzebuje rady, czy daloby sie jakos uproscic tutaj funkcje strtok? Mam za zadanie zrobic implementacje tej funkcji, jednak ani ona, ani zadna z funkcji pomocniczych nie moga byc dluzsze niz 25 linijek. Dopiero zaczelam uczyc sie programowania i skonczyly mi sie pomysly.
#include<stddef.h>
static int count_words(const char *str, char c)
{
int counter;
int idx;
int cond;
counter = 0;
cond = 0;
idx = 0;
while (str[idx])
{
if (str[idx] != c && cond == 0)
{
cond = 1;
counter++;
}
else if (str[idx] == c)
{
cond = 0;
}
idx++;
}
return (counter);
}
int wleng(char const *s, char c, int i)
{
int wrdleng;
wrdleng = 0;
while (s[i + wrdleng] != '\0' && s[i + wrdleng] != c)
{
wrdleng++;
}
return (wrdleng);
}
char **mallocsen(char const *s, char c)
{
char **sent;
sent = (char **)malloc((count_words(s, c) + 1) * sizeof(*sent));
if (!sent)
{
return (NULL);
}
return (sent);
}
char *mallocword(char const *s, char c, int wrdleng)
{
char *wordx;
wordx = (char *)malloc((wrdleng + 1) * sizeof(char));
if (!wordx)
{
return (NULL);
}
return (wordx);
}
char **strtok(char const *s, char c)
{
int i;
int wrdleng;
int j;
int k;
char *word;
char **sentence;
sentence = mallocsen(s, c);
if (!sentence)
return (0);
i = 0;
j = 0;
while (s[i] != 0 && c != '\0')
{
while (s[i] == c)
i++;
if (s[i] == '\0')
break ;
wrdleng = wleng(s, c, i);
k = 0;
word = mallocword(s, c, wrdleng);
if (!word)
return (0);
while (k < wrdleng)
word[k++] = s[i++];
word[wrdleng] = '\0';
sentence[j] = word;
j++;
}
sentence[j] = NULL;
return (sentence);
}
int main(void)
{
char **arr;
char *phrase = " Helleo,Flaevlio\t Wuensche! ";
arr = strtok(phrase, 'e');
printf("%s\n", arr[0]);
printf("%s\n", arr[1]);
printf("%s\n", arr[2]);
printf("%s\n", arr[3]);
printf("%s\n", arr[4]);
printf("%s\n", arr[5]);
}