source: Main/trunk/Common/string.c@ 12

Last change on this file since 12 was 6, checked in by Nishi, on Sep 13, 2024 at 7:28:20 PM

vhost

  • Property svn:keywords set to Id
File size: 2.0 KB
Line 
1/* $Id: string.c 6 2024-09-13 10:28:20Z nishi $ */
2
3#include <string.h>
4#include <stdlib.h>
5#include <stdbool.h>
6#include <ctype.h>
7
8char* cm_strcat(const char* a, const char* b) {
9 char* str = malloc(strlen(a) + strlen(b) + 1);
10 memcpy(str, a, strlen(a));
11 memcpy(str + strlen(a), b, strlen(b));
12 str[strlen(a) + strlen(b)] = 0;
13 return str;
14}
15
16char* cm_strdup(const char* str) { return cm_strcat(str, ""); }
17
18char* cm_trimstart(const char* str) {
19 int i;
20 for(i = 0; str[i] != 0; i++) {
21 if(str[i] != ' ' && str[i] != '\t') {
22 return cm_strdup(str + i);
23 }
24 }
25 return cm_strdup("");
26}
27
28char* cm_trimend(const char* str) {
29 char* s = cm_strdup(str);
30 int i;
31 for(i = strlen(s) - 1; i >= 0; i--) {
32 if(s[i] != '\t' && s[i] != ' ') {
33 s[i + 1] = 0;
34 break;
35 }
36 }
37 return s;
38}
39
40char* cm_trim(const char* str) {
41 char* tmp = cm_trimstart(str);
42 char* s = cm_trimend(tmp);
43 free(tmp);
44 return s;
45}
46
47char** cm_split(const char* str, const char* by) {
48 int i;
49 char** r = malloc(sizeof(*r));
50 r[0] = NULL;
51 char* b = malloc(1);
52 b[0] = 0;
53 char cbuf[2];
54 cbuf[1] = 0;
55 bool dq = false;
56 bool sq = false;
57 for(i = 0;; i++) {
58 int j;
59 bool has = false;
60 for(j = 0; by[j] != 0; j++) {
61 if(by[j] == str[i]) {
62 has = true;
63 break;
64 }
65 }
66 if(!(dq || sq) && (has || str[i] == 0)) {
67 if(strlen(b) > 0) {
68 char** old = r;
69 int j;
70 for(j = 0; old[j] != NULL; j++)
71 ;
72 r = malloc(sizeof(*r) * (j + 2));
73 for(j = 0; old[j] != NULL; j++) r[j] = old[j];
74 r[j] = b;
75 r[j + 1] = NULL;
76 free(old);
77 }
78 b = malloc(1);
79 b[0] = 0;
80 if(str[i] == 0) break;
81 } else {
82 if(str[i] == '"' && !sq) {
83 dq = !dq;
84 } else if(str[i] == '\'' && !dq) {
85 sq = !sq;
86 } else {
87 cbuf[0] = str[i];
88 char* tmp = b;
89 b = cm_strcat(tmp, cbuf);
90 free(tmp);
91 }
92 }
93 }
94 free(b);
95 return r;
96}
97
98bool cm_strcaseequ(const char* a, const char* b) {
99 if(a == NULL) return false;
100 if(b == NULL) return false;
101 if(strlen(a) != strlen(b)) return false;
102 int i;
103 for(i = 0; a[i] != 0; i++) {
104 if(tolower(a[i]) != tolower(b[i])) return false;
105 }
106 return true;
107}
Note: See TracBrowser for help on using the repository browser.