From 5bc9df836e9cd83548d6bdae60df4748c7e3da28 Mon Sep 17 00:00:00 2001 From: James <101812526+WoodchuckXL@users.noreply.github.com> Date: Wed, 17 Jun 2026 12:36:11 -0400 Subject: [PATCH] Add substring fn to string class --- src/classes/strng.c | 31 ++++++++++++++++++++++++++++++- src/classes/strng.h | 1 + test/string/substring.morpho | 14 ++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 test/string/substring.morpho diff --git a/src/classes/strng.c b/src/classes/strng.c index 2d1ca699..a30c3b62 100644 --- a/src/classes/strng.c +++ b/src/classes/strng.c @@ -176,6 +176,7 @@ int string_countchars(objectstring *s) { /** Get a pointer to the i'th character of a string */ char *string_index(objectstring *s, int i) { + if (i<0) return NULL; int n=0; for (char *c = s->string; *c!='\0'; ) { if (i==n) return (char *) c; @@ -288,6 +289,33 @@ value String_split(vm *v, int nargs, value *args) { return out; } +/** Gets a substring of the string */ +value String_substring(vm *v, int nargs, value *args) { + objectstring *slf = MORPHO_GETSTRING(MORPHO_SELF(args)); + value out=MORPHO_NIL; + int begin=MORPHO_GETINTEGERVALUE(MORPHO_GETARG(args, 0)); + int end=MORPHO_GETINTEGERVALUE(MORPHO_GETARG(args, 1)); + + if (end<0 || (begin>=slf->length && begin>0) || end-begin<0) { + out=MORPHO_OBJECT(object_stringwithsize(0)); + } else { + begin=(begin<0) ? 0 : begin; + end=(end>slf->length) ? slf->length : end; + char *cstr = string_index(slf, begin); + + // Get size in bytes of the chars to include + char *cstrend = cstr; + for (int i = 0; i