From 78683cb984a54c8480f7785c5e577717bb242bc2 Mon Sep 17 00:00:00 2001 From: tjann Date: Sat, 2 Nov 2024 13:54:00 +0300 Subject: [PATCH] Description for TriFuncSplitPreserve.java added + bug fixed --- .../org/cactoos/func/TriFuncSplitPreserve.java | 16 +++++++++++++--- .../java/org/cactoos/text/SplitPreserveTest.java | 8 ++++---- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/cactoos/func/TriFuncSplitPreserve.java b/src/main/java/org/cactoos/func/TriFuncSplitPreserve.java index 2c995aba1..c0d6e257f 100644 --- a/src/main/java/org/cactoos/func/TriFuncSplitPreserve.java +++ b/src/main/java/org/cactoos/func/TriFuncSplitPreserve.java @@ -29,7 +29,17 @@ import org.cactoos.list.ListOf; /** - * Used for avoiding static method calls. + * A String splitter preserving all tokens. + * Unlike regular Split, stores empty "" tokens + * created by adjacent regex separators. + * + *

+ * Examples: + * 1) text - " hello there", regex - " " + * result: ["", "hello", "there", ""] + * 2) text - "aaa", regex - "a" + * result: ["", "", "", ""] + *

* * @since 0.0 */ @@ -46,14 +56,14 @@ public Collection apply( int start = 0; int pos = str.indexOf(regex); while (pos >= start) { - if (lmt > 0 && ret.size() == lmt) { + if (lmt > 0 && ret.size() == lmt || regex.isEmpty()) { break; } ret.add(str.substring(start, pos)); start = pos + regex.length(); pos = str.indexOf(regex, start); } - if (lmt <= 0 || ret.size() < lmt) { + if (lmt <= 0 || ret.size() < lmt || regex.isEmpty()) { if (start < str.length()) { ret.add(str.substring(start)); } else if (start == str.length()) { diff --git a/src/test/java/org/cactoos/text/SplitPreserveTest.java b/src/test/java/org/cactoos/text/SplitPreserveTest.java index 575e6b9a4..01dc0a4c5 100644 --- a/src/test/java/org/cactoos/text/SplitPreserveTest.java +++ b/src/test/java/org/cactoos/text/SplitPreserveTest.java @@ -42,7 +42,7 @@ final class SplitPreserveTest { @Test void checkingSplit() { - String txt = " "; + String txt = "aaa"; final String msg = "Adjacent separators must create an empty element"; ArrayList array = new ArrayList<>(4); array.add(new TextOf("")); @@ -54,7 +54,7 @@ void checkingSplit() { this.getLength( new Split( new TextOf(txt), - new TextOf(" ") + new TextOf("a") ).iterator() ), IsNot.not( @@ -103,7 +103,7 @@ int getLength(final Iterator iter) { @Test void checkingSplitPreserveTokens() { - String txt = " "; + String txt = "aaa"; final String msg = "Adjacent separators must create an empty element"; ArrayList array = new ArrayList<>(4); array.add(new TextOf("")); @@ -115,7 +115,7 @@ void checkingSplitPreserveTokens() { this.getLength( new SplitPreserveAllTokens( new TextOf(txt), - new TextOf(" ") + new TextOf("a") ).iterator() ), Matchers.equalTo(