Skip to content

Commit

Permalink
Merge pull request #1749 from HaidarJbeily7/master
Browse files Browse the repository at this point in the history
Feat: add support for negative value to get tail from the string
  • Loading branch information
yegor256 authored Nov 26, 2024
2 parents b6f0d63 + 7a0f591 commit 4482ed9
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/main/java/org/cactoos/text/Sub.java
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,22 @@ public Sub(final Text text, final Func<? super String, Integer> start,
new Mapped(
origin -> {
int begin = start.apply(origin);
if (begin < 0) {
begin = origin.length() + begin;
}
if (begin < 0) {
begin = 0;
}
int finish = end.apply(origin);
if (origin.length() < finish) {
if (finish < 0) {
finish = origin.length() + finish;
}
if (finish > origin.length()) {
finish = origin.length();
}
if (finish < 0) {
finish = 0;
}
return origin.substring(begin, finish);
},
text
Expand Down
27 changes: 27 additions & 0 deletions src/test/java/org/cactoos/text/SubTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,31 @@ void cutTextWithStart() {
).affirm();
}

@Test
void cutTextWithNegativeStart() {
new Assertion<>(
"Can't cut text with negative start",
new Sub("hello world", -5),
new HasString("world")
).affirm();
}

@Test
void cutTextWithNegativeStartAndEnd() {
new Assertion<>(
"Can't cut text with negative start and positive end",
new Sub("hello world", -5, 8),
new HasString("wo")
).affirm();
}

@Test
void cutTextWithNegativeStartAndNegativeEnd() {
new Assertion<>(
"Can't cut text with negative start and negative end",
new Sub("hello world", -5, -2),
new HasString("wor")
).affirm();
}

}

0 comments on commit 4482ed9

Please sign in to comment.