From 7f91cbc39701ea97d2ae16966299f08485b8f0cc Mon Sep 17 00:00:00 2001 From: kobewi Date: Sun, 31 Oct 2021 15:36:16 +0100 Subject: [PATCH] Expose String.get_slice (cherry picked from commit e5725c7debd025be9f7b475527324b4b934fed58) --- core/variant_call.cpp | 2 ++ doc/classes/String.xml | 14 ++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/core/variant_call.cpp b/core/variant_call.cpp index 12f36bab4e..4a44cf641c 100644 --- a/core/variant_call.cpp +++ b/core/variant_call.cpp @@ -245,6 +245,7 @@ struct _VariantCall { VCALL_LOCALMEM3R(String, count); VCALL_LOCALMEM3R(String, countn); VCALL_LOCALMEM2R(String, substr); + VCALL_LOCALMEM2R(String, get_slice); VCALL_LOCALMEM2R(String, find); VCALL_LOCALMEM1R(String, find_last); VCALL_LOCALMEM2R(String, findn); @@ -1633,6 +1634,7 @@ void register_variant_methods() { ADDFUNC1R(STRING, INT, String, naturalnocasecmp_to, STRING, "to", varray()); ADDFUNC0R(STRING, INT, String, length, varray()); ADDFUNC2R(STRING, STRING, String, substr, INT, "from", INT, "len", varray(-1)); + ADDFUNC2R(STRING, STRING, String, get_slice, STRING, "delimiter", INT, "slice", varray()); ADDFUNC2R(STRING, INT, String, find, STRING, "what", INT, "from", varray(0)); diff --git a/doc/classes/String.xml b/doc/classes/String.xml index b11931e214..f6eac0138a 100644 --- a/doc/classes/String.xml +++ b/doc/classes/String.xml @@ -335,6 +335,19 @@ If the string is a valid file path, returns the filename. + + + + + + Splits a string using a [code]delimiter[/code] and returns a substring at index [code]slice[/code]. Returns an empty string if the index doesn't exist. + This is a more performant alternative to [method split] for cases when you need only one element from the array at a fixed index. + Example: + [codeblock] + print("i/am/example/string".get_slice("/", 2)) # Prints 'example'. + [/codeblock] + + @@ -690,6 +703,7 @@ Splits the string by a [code]delimiter[/code] string and returns an array of the substrings. The [code]delimiter[/code] can be of any length. If [code]maxsplit[/code] is specified, it defines the number of splits to do from the left up to [code]maxsplit[/code]. The default value of [code]0[/code] means that all items are split. + If you need only one element from the array at a specific index, [method get_slice] is a more performant option. Example: [codeblock] var some_string = "One,Two,Three,Four"