sv_strstr

This commit is contained in:
Randy Jordan 2025-07-11 11:00:57 -05:00
parent 36038ef7ba
commit 4d90e7dba7
Signed by: Randy-Jordan
GPG Key ID: 153FF450FDC74D1A
3 changed files with 35 additions and 2 deletions

View File

@ -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

View File

@ -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);
}

22
tests/10_sv_strstr.c Normal file
View File

@ -0,0 +1,22 @@
#define DEBUG
#include "../include/sv.h"
#include "../include/except.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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;
}