From 14b6304bb416795ca1016e9ce5f052b0861e5a48 Mon Sep 17 00:00:00 2001 From: ubq323 Date: Fri, 9 Aug 2024 23:37:13 +0100 Subject: add ssplit --- lib.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'lib.c') diff --git a/lib.c b/lib.c index dddd377..5d5d2b3 100644 --- a/lib.c +++ b/lib.c @@ -94,6 +94,27 @@ static Val fn_spend(State *S, int nargs, Val *args) { } return VAL_OBJ(objstring_take(S, new, len)); } +static Val fn_ssplit(State *S, int nargs, Val *args) { + CHECK(nargs==2,"need exactly 2 args for ssplit"); + CHECK(IS_STRING(args[0]) && IS_STRING(args[1]), "need two strings for ssplit"); + ObjString *delim = AS_STRING(args[0]); + ObjString *text = AS_STRING(args[1]); + CHECK(delim->len == 1, "need length-1 delimiter"); + char delimc = delim->d[0]; + + ObjArr *out = objarr_new(S); + int start = 0; + for (int i = 0; i <= text->len; i++) { + if (text->d[i] == delimc || i == text->len) { + ObjString *new = objstring_copy(S, &text->d[start], i-start); + objarr_append(S, out, VAL_OBJ(new)); + start = i + 1; + } + } + + return VAL_OBJ(out); +} + typedef struct { @@ -111,6 +132,7 @@ static BuiltinFunc builtin_funcs[] = { { "#", fn_len }, { ",", fn_pend }, { "s,", fn_spend }, + { "ssplit", fn_ssplit }, { 0 }, }; -- cgit v1.2.3