-
Notifications
You must be signed in to change notification settings - Fork 16
/
string_util.h
82 lines (66 loc) · 1.69 KB
/
string_util.h
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
#ifndef __STRING_UTIL_H
#define __STRING_UTIL_H
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <ctype.h>
int starts_with(char *s, const char *with) {
return strncmp(s, with, strlen(with)) == 0;
}
int ends_with(const char *s, const char *with) {
int len_s = strlen(s);
int len_with = strlen(with);
if (len_with <= len_s) {
return strncmp(s + len_s - len_with, with, len_with) == 0;
} else {
return 0;
}
}
int contains(const char *s1, const char *s2) {
return strstr(s1, s2) != NULL;
}
char* substr(const char* input, int offset, int len, char* dest) {
int input_len = strlen (input);
if (offset + len > input_len) {
return NULL;
}
strncpy(dest, input + offset, len);
return dest;
}
int ends_with_extension(const char *inp) {
int end_pos = strlen(inp);
while (--end_pos >= 0) {
if (inp[end_pos] == '.') return 1;
if (!isalpha(inp[end_pos])) return 0;
}
return 0;
}
char *concat(const char *s1, const char *s2) {
char *r = malloc(strlen(s1) + strlen(s2) + 1);
strcpy(r, s1);
strcat(r, s2);
return r;
}
char *concat3(const char *s1, const char *s2, const char *s3) {
char *r = malloc(strlen(s1) + strlen(s2) + strlen(s3) + 1);
strcpy(r, s1);
strcat(r, s2);
strcat(r, s3);
return r;
}
char *concat4(const char *s1, const char *s2, const char *s3, const char *s4) {
char *r = malloc(strlen(s1) + strlen(s2) + strlen(s3) + strlen(s4) + 1);
strcpy(r, s1);
strcat(r, s2);
strcat(r, s3);
strcat(r, s4);
return r;
}
char *strappend(const char *s1, const char *s2) {
char *r = malloc(strlen(s1) + strlen(s2) + 1);
strcpy(r, s1);
strcat(r, s2);
assert(strlen(r) == strlen(s1) + strlen(s2));
return r;
}
#endif