Added strstr
This commit is contained in:
@@ -26,6 +26,7 @@ extern struct String_View sv_before_delim(const struct String_View sv,
|
||||
const char *delims);
|
||||
extern struct String_View sv_after_delim(const struct String_View sv,
|
||||
const char *delims);
|
||||
|
||||
extern struct String_View sv_str_str(const struct String_View haystack,
|
||||
const struct String_View needle);
|
||||
|
||||
#endif
|
||||
|
||||
14
src/sv.c
14
src/sv.c
@@ -80,7 +80,6 @@ struct String_View sv_before_delim(const struct String_View sv,const char *delim
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
struct String_View sv_after_delim(const struct String_View sv, const char *delims){
|
||||
// Handle NULL pointer or empty string view
|
||||
if (sv.buf == NULL || delims == NULL) {
|
||||
@@ -103,3 +102,16 @@ struct String_View sv_after_delim(const struct String_View sv, const char *delim
|
||||
struct String_View result = sv_strn(sv.buf, i);
|
||||
return result;
|
||||
}
|
||||
|
||||
struct String_View sv_str_str(const struct String_View haystack, const struct String_View 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);
|
||||
}
|
||||
|
||||
|
||||
20
tests/10_strstr.c
Normal file
20
tests/10_strstr.c
Normal file
@@ -0,0 +1,20 @@
|
||||
#define DEBUG
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include "../include/sv.h"
|
||||
|
||||
int main(void){
|
||||
const char *s = "Hello World!,Goodbye World!";
|
||||
const char *n = "Goodbye";
|
||||
const char *test = "Goodbye World!";
|
||||
struct String_View sv = sv_strn(s, strlen(s));
|
||||
struct String_View sv2 = sv_strn(n, strlen(n));
|
||||
|
||||
struct String_View found = sv_str_str(sv, sv2);
|
||||
assert(found.len == strlen(test));
|
||||
assert( memcmp(found.buf, test, found.len) == 0);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
Reference in New Issue
Block a user