[pacman-dev] [PATCH] Add str_endswith() utility function

Anatol Pomozov anatol.pomozov at gmail.com
Tue Apr 21 18:42:10 UTC 2020


It provides an easy way to check whether a string ends with a given
suffix.

Signed-off-by: Anatol Pomozov <anatol.pomozov at gmail.com>
---
 src/common/util-common.c | 18 ++++++++++++++++++
 src/common/util-common.h |  2 ++
 2 files changed, 20 insertions(+)

diff --git a/src/common/util-common.c b/src/common/util-common.c
index 7d43ac0d..11ffc705 100644
--- a/src/common/util-common.c
+++ b/src/common/util-common.c
@@ -198,6 +198,24 @@ char *strndup(const char *s, size_t n)
 }
 #endif
 
+/** Helper function for check whether a string ends with a given suffix
+ * @param str a string
+ * @param suffix we want to check
+ * @return 0 in case if the given string does not end with the suffix,
+ *    a non-zero value otherwise.
+ */
+int str_endswith(const char *str, const char *suffix)
+{
+	int str_len = strlen(str);
+	int suffix_len = strlen(suffix);
+
+	if(suffix_len > str_len) {
+		return 0;
+	}
+
+	return !strcmp(str + str_len - suffix_len, suffix);
+}
+
 void wordsplit_free(char **ws)
 {
 	if(ws) {
diff --git a/src/common/util-common.h b/src/common/util-common.h
index 483d5da4..6b66be3e 100644
--- a/src/common/util-common.h
+++ b/src/common/util-common.h
@@ -35,6 +35,8 @@ char **wordsplit(const char *str);
 
 size_t strtrim(char *str);
 
+int str_endswith(const char *str, const char *suffix);
+
 #ifndef HAVE_STRNDUP
 char *strndup(const char *s, size_t n);
 #endif
-- 
2.26.2


More information about the pacman-dev mailing list