-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsplit_string_static.c
98 lines (88 loc) · 2.6 KB
/
split_string_static.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* split_string_static.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aldokezer <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/06 14:44:18 by orezek #+# #+# */
/* Updated: 2023/11/07 22:34:44 by aldokezer ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
//cc split_string_static.c get_next_line_utils.c && ./a.out
int new_line_counter(char *str)
{
int counter;
counter = 0;
while(*str++)
{
if (*str == '\n')
counter++;
}
return (counter);
}
int find_new_line_position( char *str)
{
int i;
i = 0;
while (*str)
{
if (*str == '\n')
return (i);
i++;
str++;
}
return (-1);
}
// Generator function that returns string and retains state
// between calls. It will return NULL when there is no more string to return.
char *ft_nlsplit_generator(char *str)
{
static char *arr;
char *result;
int new_line_position;
new_line_position = 0;
if (!arr)
arr = strdup(str);
if (arr[0] == '\0')
{
free(arr);
return (arr = NULL);
}
new_line_position = find_new_line_position(arr);
if (new_line_position >= 0)
{
result = malloc(sizeof(char) * (new_line_position + 2));
result = strncpy(result, arr, new_line_position + 1);
result[new_line_position + 1] = '\0';
arr = memmove(arr, arr + new_line_position + 1, ft_strlen(arr) - new_line_position);
return (result);
}
else if (new_line_position == -1)
{
result = malloc(sizeof(char) * ft_strlen(arr) + 1);
result = strcpy(result, arr);
arr[0] = '\0';
return (result);
}
free(arr);
return (arr = NULL);
}
int main(void)
{
char *str = "ahoj,ja jsem aldo\na tohle je test\na tohle je dalsi test\n";
char *result;
result = ft_nlsplit_generator(str);
while (result != NULL)
{
printf("%s", result);
free(result);
result = ft_nlsplit_generator(str);
}
free(result);
return (0);
}
// vraci get_next_line string zakoceny new line nebo nulou? - vraci string vcetne new line a nuly
// vrati strncpy string zakonceny nulou? - nevraci!
// pouziju memmove k premisteni byte z jedne casti na druhou