]> mj.ucw.cz Git - libucw.git/blob - ucw/str-fix.c
tableprinter: removed column type macros
[libucw.git] / ucw / str-fix.c
1 /*
2  *      UCW Library -- Matching Prefixes and Suffixes
3  *
4  *      (c) 2011 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/string.h>
12
13 #include <string.h>
14
15 int
16 str_has_prefix(const char *str, const char *prefix)
17 {
18   size_t pxlen = strlen(prefix);
19   return !strncmp(str, prefix, pxlen);
20 }
21
22 int
23 str_has_suffix(const char *str, const char *suffix)
24 {
25   size_t sxlen = strlen(suffix);
26   size_t len = strlen(str);
27
28   if (len < sxlen)
29     return 0;
30   else
31     return !strcmp(str + len - sxlen, suffix);
32 }
33
34 int
35 str_hier_prefix(const char *str, const char *prefix, uint sep)
36 {
37   while (*str && *prefix)
38     {
39       size_t sl=0, pl=0;
40       while (str[sl] && (uint) str[sl] != sep)
41         sl++;
42       while (prefix[pl] && (uint) prefix[pl] != sep)
43         pl++;
44       if (sl != pl || memcmp(str, prefix, sl))
45         return 0;
46       str += sl, prefix += pl;
47       if (!*str)
48         return !*prefix;
49       if (!*prefix)
50         return 1;
51       str++, prefix++;
52     }
53   return !*prefix;
54 }
55
56 int
57 str_hier_suffix(const char *str, const char *suffix, uint sep)
58 {
59   const char *st = str + strlen(str);
60   const char *sx = suffix + strlen(suffix);
61   while (st > str && sx > suffix)
62     {
63       size_t sl=0, pl=0;
64       while (st-sl > str && (uint) st[-sl-1] != sep)
65         sl++;
66       while (sx-pl > suffix && (uint) sx[-pl-1] != sep)
67         pl++;
68       if (sl != pl || memcmp(st-sl, sx-pl, sl))
69         return 0;
70       st -= sl, sx -= pl;
71       if (st == str)
72         return (sx == suffix);
73       if (sx == suffix)
74         return 1;
75       st--, sx--;
76     }
77   return (sx == suffix);
78 }
79
80 #ifdef TEST
81
82 #include <stdio.h>
83
84 int main(int argc, char **argv)
85 {
86   if (argc != 4)
87     return 1;
88
89   int ret;
90   switch (argv[1][0])
91     {
92     case 'p':
93       ret = str_has_prefix(argv[2], argv[3]);
94       break;
95     case 's':
96       ret = str_has_suffix(argv[2], argv[3]);
97       break;
98     case 'P':
99       ret = str_hier_prefix(argv[2], argv[3], '.');
100       break;
101     case 'S':
102       ret = str_hier_suffix(argv[2], argv[3], '.');
103       break;
104     default:
105       return 1;
106     }
107   printf("%s\n", (ret ? "YES" : "NO"));
108   return 0;
109 }
110
111 #endif