-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjts_string.c
110 lines (68 loc) · 1.28 KB
/
jts_string.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
#include "jts_string.h"
char* jts_strrev(const char *restrict s)
{
const size_t length = strlen(s);
// The caller must free me.
char *r = calloc(1, length + 1);
r[length] = '\0';
if (r == NULL) goto tag_return;
size_t c = 0;
for (size_t i = length; i >= 0; i--) {
if (s[i] == '\0') continue;
r[c] = s[i];
c++;
if (i == 0) break;
}
tag_return:
return r;
}
bool jts_ispalendrome(const char *restrict s)
{
bool ispalendrome = false;
char *r = jts_strrev(s);
if (s == NULL || r == NULL) {
goto tag_return;
}
if (strcmp(s, r) == 0) {
ispalendrome = true;
}
tag_return:
free(r);
return ispalendrome;
}
intmax_t jts_numinstances(const char *restrict s, const char c)
{
intmax_t instances = 0;
if (s == NULL) {
instances = -1;
goto err;
}
size_t length = strlen(s);
for (size_t i = 0; i < length; i++) {
if (s[i] == c) {
instances++;
}
}
err:
return instances;
}
char **jts_copy_argv(int argc, char **argv)
{
if (argc <= 0 || argv == NULL) {
return NULL;
}
char **s = calloc(argc, sizeof(char*));
if (s == NULL) {
return NULL;
}
int len = 0;
for (int i = 0; i < argc; i++) {
len = strlen(argv[i]);
s[i] = calloc(len + 1, 1);
if (s[i] == NULL) {
break;
}
strncpy(s[i], argv[i], len);
}
return s;
}