Added before/after delims

This commit is contained in:
2025-10-18 15:05:22 -05:00
parent f9e963d7e3
commit c1e7ca3bca
4 changed files with 88 additions and 0 deletions

View File

@@ -22,5 +22,10 @@ extern struct String_View sv_trim_right(struct String_View sv);
extern struct String_View sv_trim(struct String_View sv);
extern int sv_eq(const struct String_View sv1, const struct String_View sv2);
extern int sv_casecmp( const struct String_View sv1, const struct String_View sv2);
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);
#endif

View File

@@ -56,3 +56,50 @@ int sv_casecmp(const struct String_View sv1, const struct String_View sv2){
if (i < sv2.len) return -1;
return 0;
}
struct String_View sv_before_delim(const struct String_View sv,const char *delims){
// Handle NULL pointer or empty string view
if (sv.buf == NULL || delims == NULL) {
return sv_strn(NULL, 0);
}
size_t i = 0;
while (i < sv.len) {
// Check if the current character is a delimiter
for (size_t j = 0; delims[j] != '\0'; j++) {
if (sv.buf[i] == delims[j]) {
struct String_View result = sv_strn(sv.buf, i);
return result;
}
}
i++;
}
// Return the whole string if no delimiter was found
struct String_View result = sv_strn(sv.buf, i);
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) {
return sv_strn(NULL, 0);
}
size_t i = 0;
while (i < sv.len) {
// Check if the current character is a delimiter
for (size_t j = 0; delims[j] != '\0'; j++) {
if (sv.buf[i] == delims[j]) {
struct String_View result = sv_strn(sv.buf+i+1, sv.len-i-1);
return result;
}
}
i++;
}
// Return the whole string if no delimiter was found
struct String_View result = sv_strn(sv.buf, i);
return result;
}

View File

@@ -0,0 +1,18 @@
#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 *s3 = "Hello World!";
struct String_View sv = sv_strn(s, strlen(s));
struct String_View sv2 = sv_before_delim(sv,",");
assert(sv2.len == strlen(s3));
assert( memcmp(sv2.buf, s3, sv2.len) == 0);
return EXIT_SUCCESS;
}

18
tests/09_after_delims.c Normal file
View File

@@ -0,0 +1,18 @@
#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 *s3 = "Goodbye World!";
struct String_View sv = sv_strn(s, strlen(s));
struct String_View sv2 = sv_after_delim(sv,",");
assert(sv2.len == strlen(s3));
assert( memcmp(sv2.buf, s3, sv2.len) == 0);
return EXIT_SUCCESS;
}