-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_str_2.c
114 lines (106 loc) · 2.31 KB
/
utils_str_2.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <stdlib.h>
#include "main.h"
/**
* sub_str - Makes a copy of a subset of a string
* @str: The string containing the subset
* @i: The starting position of the subset
* @can_free: Specifies if the given string can be freed
*
* Return: The string subset, otherwise NULL
*/
char *sub_str(char *str, int i, char can_free)
{
char *new_str;
int len = str_len(str);
char start = i < 0 ? len + i : i;
int size = i < 0 ? -i : len - start;
int j;
new_str = malloc(sizeof(char) * (size + 1));
if (str)
{
for (j = 0; *(str + start) != 0; j++)
{
*(new_str + j) = *(str + start);
start++;
}
*(new_str + j) = '\0';
}
if (can_free)
free(str);
return (new_str);
}
/**
* trim_start - Makes a trimmed copy of a string
* @str: The string whose beginning is to be trimmed
* @c: The character to strip from the beginning of the string
* @can_free: Specifies if the given string can be freed
*
* Return: The trimmed copy, otherwise NULL
*/
char *trim_start(char *str, char c, char can_free)
{
int i, j, len;
char *new_str;
for (i = 0; *(str + i) != '\0' && *(str + i) == c; i++)
;
len = str_len(str) - i;
new_str = malloc(sizeof(char) * (len + 1));
if (new_str)
{
for (j = 0; *(str + i) != '\0'; i++)
{
*(new_str + j) = *(str + i);
j++;
}
*(new_str + j) = '\0';
if (can_free)
free(str);
}
return (new_str);
}
/**
* trim_end - Makes a trimmed copy of a string
* @str: The string whose ending is to be trimmed
* @c: The character to strip from the end of the string
* @can_free: Specifies if the given string can be freed
*
* Return: The trimmed copy, otherwise NULL
*/
char *trim_end(char *str, char c, char can_free)
{
char *new_str;
int len = str_len(str);
int i, j;
for (i = len - 1; i >= 0 && *(str + i) == c; i--)
;
new_str = malloc(sizeof(char) * (len + 1));
if (new_str)
{
for (j = 0; j <= i; j++)
*(new_str + j) = *(str + j);
*(new_str + j) = '\0';
if (can_free)
free(str);
}
return (new_str);
}
/**
* str_copy - Makes a copy of a string
* @str: The string to copy
*
* Return: The copied string, otherwise NULL
*/
char *str_copy(char *str)
{
char *new_str;
int i;
int len = str_len(str);
new_str = malloc(sizeof(char) * (len + 1));
if (new_str)
{
for (i = 0; i < len; i++)
*(new_str + i) = *(str + i);
*(new_str + i) = '\0';
}
return (new_str);
}