From 0b27893c59be6b6bd231e4f3e1198ce8e00859e1 Mon Sep 17 00:00:00 2001 From: Justin Lin Date: Wed, 29 Mar 2017 13:20:17 +0800 Subject: [PATCH] added split_str --- README.md | 1 + docs/lib-split_str.md | 16 ++++++++++++++++ src/split_str.scad | 22 ++++++++++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 docs/lib-split_str.md create mode 100644 src/split_str.scad 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