From 4d90e7dba770cfa5e0b0525874229c83f5e8d0ad Mon Sep 17 00:00:00 2001 From: Randy Jordan Date: Fri, 11 Jul 2025 11:00:57 -0500 Subject: [PATCH] sv_strstr --- include/sv.h | 4 ++-- src/sv.c | 11 +++++++++++ tests/10_sv_strstr.c | 22 ++++++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 tests/10_sv_strstr.c diff --git a/include/sv.h b/include/sv.h index 0130a33..d0e601d 100644 --- a/include/sv.h +++ b/include/sv.h @@ -24,7 +24,7 @@ SV sv_trim_left(SV s); SV sv_trim_right(SV s); int sv_cmp(const SV s1, const SV s2); int sv_casecmp(const SV s1, const SV s2); -SV after_delim(const SV s, char *delims); SV before_delim(const SV s, char *delims); - +SV after_delim(const SV s, char *delims); +SV sv_strstr(const SV haystack, const SV needle); #endif diff --git a/src/sv.c b/src/sv.c index 6736250..279e8b2 100644 --- a/src/sv.c +++ b/src/sv.c @@ -100,3 +100,14 @@ SV after_delim(const SV s, char *delims) { SV result = sv_strn(s.buf, i); return result; } +SV sv_strstr(const SV haystack, const SV needle){ + size_t i; + if (needle.len > haystack.len) return sv_strn(NULL,0); + if (needle.len == 0) return haystack; + for (i = 0; i <= haystack.len - needle.len; i++) { + if (memcmp(haystack.buf + i, needle.buf, needle.len) == 0) { + return sv_strn(haystack.buf + i, haystack.len -i); + } + } + return sv_strn(NULL,0); +} diff --git a/tests/10_sv_strstr.c b/tests/10_sv_strstr.c new file mode 100644 index 0000000..cf59384 --- /dev/null +++ b/tests/10_sv_strstr.c @@ -0,0 +1,22 @@ +#define DEBUG +#include "../include/sv.h" +#include "../include/except.h" +#include +#include +#include + +int main(void){ + const char *haystack = "Hello World, this is a test."; + const char *needle = "World,"; + const char *result = "World, this is a test."; + + SV sv_haystack = sv_strn(haystack,strlen(haystack)); + SV sv_needle = sv_strn(needle,strlen(needle)); + SV sv_res = sv_strn(result,strlen(result)); + + SV test = sv_strstr(sv_haystack,sv_needle); + + ASSERTED(sv_cmp(sv_res,test) == 0); + + return EXIT_SUCCESS; +}