-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1-split_string.c
More file actions
126 lines (111 loc) · 2.23 KB
/
1-split_string.c
File metadata and controls
126 lines (111 loc) · 2.23 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "main.h"
/**
* split_string - splits a string
* @str: string to be split
* Description - splits a string using strtok. Made for the purpose of
* splitting input into shell and returning an array of
* string arguments that can be passed into an exec function.
* Also, the first argument of the resulting array can
* be searched for in PATH.
* Return: array of words of split string
*/
char **split_string(char *str)
{
char *str_dup;
char *word;
char **array;
int i;
int len;
int count;
if (str == NULL)
return (NULL);
count = 0;
len = _strlen(str);
str_dup = malloc(len + 1);
if (str_dup == NULL)
return (NULL);
memcpy(str_dup, str, len);
str_dup[len] = '\0';
word = strtok(str_dup, " ");
while (word != NULL)
{
count++;
word = strtok(NULL, " ");
}
free(str_dup);
array = malloc(((count + 1) * sizeof(char *)));
if (array == NULL)
{
return (NULL);
}
word = strtok(str, " ");
for (i = 0; i < count; i++)
{
array[i] = word;
word = strtok(NULL, " ");
}
array[count] = (char *)NULL;
return (array);
}
/**
* _strlen - computes the length of a string
* @str: string whose length is to be computed
* Description - computes the length of a string
* Return: integer, length of string
*/
int _strlen(char *str)
{
int i;
int lenn;
if (str == NULL)
return (0);
i = 0;
lenn = 0;
while (str[i] != 0)
{
lenn++;
i++;
}
return (lenn);
}
/**
* _putchar - writes the character c to stdout
* @c: The character to print
*
* Return: On success 1.
* On error, -1 is returned, and errno is set appropriately.
*/
int _putchar(char c)
{
if (write(STDOUT_FILENO, &c, 1) == -1)
{
perror("write");
return (1);
}
return (1);
}
/**
* _memcpy - copies bytes from a memory area to another memory area.
* @dest: destination for bytes to be copied to
* @src: source that bytes are copied from
* @n: number of bytes to be copied
* Description - copies bytes from one memory area to another using
* for loops and indices.
* Return: pointer to destination string
*/
char *_memcpy(char *dest, char *src, unsigned int n)
{
unsigned int i;
int j;
j = 0;
for (i = 0; i < n; i++)
{
*(dest + i) = src[j];
j++;
}
return (dest);
}