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