2 * UCW Library -- Matching Prefixes and Suffixes
4 * (c) 2011 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
11 #include <ucw/string.h>
16 str_has_prefix(const char *str, const char *prefix)
18 size_t pxlen = strlen(prefix);
19 return !strncmp(str, prefix, pxlen);
23 str_has_suffix(const char *str, const char *suffix)
25 size_t sxlen = strlen(suffix);
26 size_t len = strlen(str);
31 return !strcmp(str + len - sxlen, suffix);
35 str_hier_prefix(const char *str, const char *prefix, uns sep)
37 while (*str && *prefix)
40 while (str[sl] && (uns) str[sl] != sep)
42 while (prefix[pl] && (uns) prefix[pl] != sep)
44 if (sl != pl || memcmp(str, prefix, sl))
46 str += sl, prefix += pl;
57 str_hier_suffix(const char *str, const char *suffix, uns sep)
59 const char *st = str + strlen(str);
60 const char *sx = suffix + strlen(suffix);
61 while (st > str && sx > suffix)
64 while (st-sl > str && (uns) st[-sl-1] != sep)
66 while (sx-pl > suffix && (uns) sx[-pl-1] != sep)
68 if (sl != pl || memcmp(st-sl, sx-pl, sl))
72 return (sx == suffix);
77 return (sx == suffix);
84 int main(int argc, char **argv)
93 ret = str_has_prefix(argv[2], argv[3]);
96 ret = str_has_suffix(argv[2], argv[3]);
99 ret = str_hier_prefix(argv[2], argv[3], '.');
102 ret = str_hier_suffix(argv[2], argv[3], '.');
107 printf("%s\n", (ret ? "YES" : "NO"));