summaryrefslogtreecommitdiff
path: root/src/string.c
diff options
context:
space:
mode:
authordaniel <daniel@planethacker.net>2025-05-06 16:57:32 -0700
committerdaniel <daniel@planethacker.net>2025-05-06 16:57:32 -0700
commit2278df1493e064c197913e49b5d1935942d83448 (patch)
tree42f06ab2f76e2ddf228bafbb03f79621975a4534 /src/string.c
initial import
Diffstat (limited to 'src/string.c')
-rw-r--r--src/string.c56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/string.c b/src/string.c
new file mode 100644
index 0000000..805d711
--- /dev/null
+++ b/src/string.c
@@ -0,0 +1,56 @@
+/* string.c - various string-related functions that don't come with string.h */
+
+#include <string.h>
+#include <stdbool.h>
+
+/* startswith() - Check if string starts with prefix.
+ *
+ * Args:
+ * string - String to check (haystack).
+ * prefix - Prefix to check (needle).
+ *
+ * Returns:
+ * true if 'string' starts with 'prefix', otherwise false.
+ */
+bool startswith(const char *string, const char *prefix) {
+ if ((string == NULL) || (prefix == NULL)) {
+ return false;
+ }
+
+ while (*prefix) {
+ if (*prefix++ != *string++) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/* endswith() - Check if string ends with suffix.
+ *
+ * Args:
+ * string - String to check (haystack).
+ * suffix - Suffix to check (needle).
+ *
+ * Returns:
+ * true if 'string' ends with 'suffix', otherwise false.
+ */
+bool endswith(const char *string, const char *suffix) {
+ size_t string_length;
+ size_t suffix_length;
+
+ if ((string == NULL) || (suffix == NULL)) {
+ return false;
+ }
+
+ string_length = strlen(string);
+ suffix_length = strlen(suffix);
+
+ if (suffix_length > string_length) {
+ return false;
+ }
+
+ return (strncmp(string + string_length - suffix_length,
+ suffix,
+ suffix_length) == 0) ? true : false;
+}