diff --git a/README.md b/README.md index e1dccbbf..ea294f6f 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ Some modules may depend on other modules. For example, the `polyline2d` module d - Functon - [rotate_p](https://openhome.cc/eGossip/OpenSCAD/lib-rotate_p.html) - [sub_str](https://openhome.cc/eGossip/OpenSCAD/lib-sub_str.html) + - [split_str](https://openhome.cc/eGossip/OpenSCAD/lib-split_str.html) - Path - [circle_path](https://openhome.cc/eGossip/OpenSCAD/lib-circle_path.html) diff --git a/docs/lib-split_str.md b/docs/lib-split_str.md new file mode 100644 index 00000000..fcbba9ef --- /dev/null +++ b/docs/lib-split_str.md @@ -0,0 +1,16 @@ +# split_str + +Splits the given string around matches of the given delimiting character. It depeneds on the `sub_str` function so remember to `include `. + +## Parameters + +- `t` : The source string. +- `delimiter` : The delimiting character. + +## Examples + + include ; + include ; + + echo(split_str("hello,world", ",")); // ECHO: ["hello", "world"] + diff --git a/src/split_str.scad b/src/split_str.scad new file mode 100644 index 00000000..bd43e0bf --- /dev/null +++ b/src/split_str.scad @@ -0,0 +1,22 @@ +/** +* split_str.scad +* +* Splits the given string around matches of the given delimiting character. +* It depends on the sub_str function so remember to include sub_str.scad. +* +* @copyright Justin Lin, 2017 +* @license https://opensource.org/licenses/lgpl-3.0.html +* +* @see https://openhome.cc/eGossip/OpenSCAD/lib-split_str.html +* +**/ + +function _split_t_by(idxs, t, ts = [], i = -1) = + i == -1 ? _split_t_by(idxs, t, [sub_str(t, 0, idxs[0])], i + 1) : ( + i == len(idxs) - 1 ? concat(ts, sub_str(t, idxs[i] + 1)) : + _split_t_by(idxs, t, concat(ts, sub_str(t, idxs[i] + 1, idxs[i + 1])), i + 1) + ); + +function split_str(t, delimiter) = + len(search(delimiter, t)) == 0 ? + [t] : _split_t_by(search(delimiter, t, 0)[0], t); \ No newline at end of file