Change string splitting.

This commit is contained in:
Stephen Chung 2022-04-09 13:07:42 +08:00
parent 42f977862f
commit 8bd33d7b34
2 changed files with 40 additions and 16 deletions

View File

@ -9,6 +9,12 @@ Bug fixes
* Functions with `Dynamic` parameters now work in qualified calls from `import`ed modules. * Functions with `Dynamic` parameters now work in qualified calls from `import`ed modules.
Script-breaking changes
-----------------------
* `split` now splits a string by whitespaces instead of splitting it into individual characters. This is more in line with common practices.
* A new function `to_chars` for strings is added to split the string into individual characters.
Version 1.6.0 Version 1.6.0
============= =============

View File

@ -1210,22 +1210,6 @@ mod string_functions {
pub mod arrays { pub mod arrays {
use crate::{Array, ImmutableString}; use crate::{Array, ImmutableString};
/// Return an array containing all the characters of the string.
///
/// # Example
///
/// ```rhai
/// let text = "hello";
///
/// print(text.split()); // prints "['h', 'e', 'l', 'l', 'o']"
#[rhai_fn(name = "split")]
pub fn chars(string: &str) -> Array {
if string.is_empty() {
Array::new()
} else {
string.chars().map(Into::into).collect()
}
}
/// Split the string into two at the specified `index` position and return it both strings /// Split the string into two at the specified `index` position and return it both strings
/// as an array. /// as an array.
/// ///
@ -1275,6 +1259,40 @@ mod string_functions {
vec![prefix.into(), string[prefix_len..].into()] vec![prefix.into(), string[prefix_len..].into()]
} }
} }
/// Return an array containing all the characters of the string.
///
/// # Example
///
/// ```rhai
/// let text = "hello";
///
/// print(text.to_chars()); // prints "['h', 'e', 'l', 'l', 'o']"
/// ```
#[rhai_fn(name = "to_chars")]
pub fn to_chars(string: &str) -> Array {
if string.is_empty() {
Array::new()
} else {
string.chars().map(Into::into).collect()
}
}
/// Split the string into segments based on whitespaces, returning an array of the segments.
///
/// # Example
///
/// ```rhai
/// let text = "hello, world! hello, foo!";
///
/// print(text.split()); // prints ["hello,", "world!", "hello,", "foo!"]
/// ```
#[rhai_fn(name = "split")]
pub fn split_whitespace(string: &str) -> Array {
if string.is_empty() {
Array::new()
} else {
string.split_whitespace().map(Into::into).collect()
}
}
/// Split the string into segments based on a `delimiter` string, returning an array of the segments. /// Split the string into segments based on a `delimiter` string, returning an array of the segments.
/// ///
/// # Example /// # Example