From cad4c7a942692c12e26fdcdafa1096c34a1c532d Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Wed, 23 Mar 2022 14:28:45 +0800 Subject: [PATCH] Add starts_with and ends_with for strings. --- CHANGELOG.md | 1 + src/packages/string_more.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fb11d78..74aba840 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ Enhancements * Separation of constants in function calls is removed as its performance benefit is dubious. * A function `sleep` is added to block the current thread by a specified number of seconds. * `Scope::set_alias` is added to export a variable under a particular alias name. +* `starts_with` and `ends_with` are added for strings. Version 1.5.0 diff --git a/src/packages/string_more.rs b/src/packages/string_more.rs index 182ee743..6112b5a2 100644 --- a/src/packages/string_more.rs +++ b/src/packages/string_more.rs @@ -458,6 +458,35 @@ mod string_functions { *character = to_lower_char(*character) } + /// Return `true` if the string starts with a specified string. + /// + /// # Example + /// + /// ```rhai + /// let text = "hello, world!"; + /// + /// print(text.starts_with("hello")); // prints true + /// + /// print(text.starts_with("world")); // prints false + /// ``` + pub fn starts_with(string: &str, match_string: &str) -> bool { + string.starts_with(match_string) + } + /// Return `true` if the string ends with a specified string. + /// + /// # Example + /// + /// ```rhai + /// let text = "hello, world!"; + /// + /// print(text.ends_with("world!")); // prints true + /// + /// print(text.ends_with("hello")); // prints false + /// ``` + pub fn ends_with(string: &str, match_string: &str) -> bool { + string.ends_with(match_string) + } + /// Find the specified `character` in the string, starting from the specified `start` position, /// and return the first index where it is found. /// If the `character` is not found, `-1` is returned.