Subversion Repositories Tewi

Rev

Rev 5 | Rev 16 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 nishi 1
/* $Id: string.c 6 2024-09-13 10:28:20Z nishi $ */
3 nishi 2
 
3
#include <string.h>
4
#include <stdlib.h>
5 nishi 5
#include <stdbool.h>
6
#include <ctype.h>
3 nishi 7
 
8
char* 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
 
16
char* cm_strdup(const char* str) { return cm_strcat(str, ""); }
4 nishi 17
 
6 nishi 18
char* cm_trimstart(const char* str) {
4 nishi 19
	int i;
6 nishi 20
	for(i = 0; str[i] != 0; i++) {
21
		if(str[i] != ' ' && str[i] != '\t') {
4 nishi 22
			return cm_strdup(str + i);
23
		}
24
	}
25
	return cm_strdup("");
26
}
27
 
6 nishi 28
char* cm_trimend(const char* str) {
4 nishi 29
	char* s = cm_strdup(str);
30
	int i;
6 nishi 31
	for(i = strlen(s) - 1; i >= 0; i--) {
32
		if(s[i] != '\t' && s[i] != ' ') {
4 nishi 33
			s[i + 1] = 0;
34
			break;
35
		}
36
	}
37
	return s;
38
}
39
 
6 nishi 40
char* cm_trim(const char* str) {
4 nishi 41
	char* tmp = cm_trimstart(str);
42
	char* s = cm_trimend(tmp);
43
	free(tmp);
44
	return s;
45
}
5 nishi 46
 
6 nishi 47
char** cm_split(const char* str, const char* by) {
5 nishi 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;
6 nishi 57
	for(i = 0;; i++) {
5 nishi 58
		int j;
59
		bool has = false;
6 nishi 60
		for(j = 0; by[j] != 0; j++) {
61
			if(by[j] == str[i]) {
5 nishi 62
				has = true;
63
				break;
64
			}
65
		}
6 nishi 66
		if(!(dq || sq) && (has || str[i] == 0)) {
67
			if(strlen(b) > 0) {
5 nishi 68
				char** old = r;
69
				int j;
6 nishi 70
				for(j = 0; old[j] != NULL; j++)
71
					;
5 nishi 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;
6 nishi 81
		} else {
82
			if(str[i] == '"' && !sq) {
5 nishi 83
				dq = !dq;
6 nishi 84
			} else if(str[i] == '\'' && !dq) {
5 nishi 85
				sq = !sq;
6 nishi 86
			} else {
5 nishi 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
 
6 nishi 98
bool cm_strcaseequ(const char* a, const char* b) {
5 nishi 99
	if(a == NULL) return false;
100
	if(b == NULL) return false;
101
	if(strlen(a) != strlen(b)) return false;
102
	int i;
6 nishi 103
	for(i = 0; a[i] != 0; i++) {
5 nishi 104
		if(tolower(a[i]) != tolower(b[i])) return false;
105
	}
106
	return true;
107
}