From c20b7306b00881fc070b3f5e2bcc4400b04ca43f Mon Sep 17 00:00:00 2001 From: yuqing Date: Tue, 10 Jul 2018 12:47:12 +0800 Subject: [PATCH] shared_func.h: add function starts_with and ends_with --- HISTORY | 3 ++- src/shared_func.c | 30 ++++++++++++++++++++++++++++++ src/shared_func.h | 16 ++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/HISTORY b/HISTORY index 2ef819b..414dc2f 100644 --- a/HISTORY +++ b/HISTORY @@ -1,7 +1,8 @@ -Version 1.39 2018-07-07 +Version 1.39 2018-07-10 * add #@function REPLACE_VARS * #@set value can embed %{VARIABLE} + * shared_func.h: add function starts_with and ends_with Version 1.38 2018-06-26 * connection_pool.c: set err_no to 0 when success diff --git a/src/shared_func.c b/src/shared_func.c index 893a870..6fbcb75 100644 --- a/src/shared_func.c +++ b/src/shared_func.c @@ -2633,3 +2633,33 @@ const char *long2str(const int64_t n, char *buff, const bool thousands_separator } return buff; } + +bool starts_with(const char *str, const char *needle) +{ + int str_len; + int needle_len; + + str_len = strlen(str); + needle_len = strlen(needle); + if (needle_len > str_len) { + return false; + } + + return memcmp(str, needle, needle_len) == 0; +} + +bool ends_with(const char *str, const char *needle) +{ + int str_len; + int needle_len; + int start_offset; + + str_len = strlen(str); + needle_len = strlen(needle); + start_offset = str_len - needle_len; + if (start_offset < 0) { + return false; + } + + return memcmp(str + start_offset, needle, needle_len) == 0; +} diff --git a/src/shared_func.h b/src/shared_func.h index 282e96f..346f19f 100644 --- a/src/shared_func.h +++ b/src/shared_func.h @@ -756,6 +756,22 @@ static inline const char *long_to_comma_str(const int64_t n, char *buff) return long2str(n, buff, true); } +/** if the string starts with the needle string + * parameters: + * str: the string to detect + * needle: the needle string + * return: true for starts with the needle string, otherwise false +*/ +bool starts_with(const char *str, const char *needle); + +/** if the string ends with the needle string + * parameters: + * str: the string to detect + * needle: the needle string + * return: true for ends with the needle string, otherwise false +*/ +bool ends_with(const char *str, const char *needle); + #ifdef __cplusplus } #endif