From ea716aafc1fb7ee2a283e39ef2adea147d993a38 Mon Sep 17 00:00:00 2001 From: gs2018git Date: Mon, 24 Dec 2018 17:28:01 -0500 Subject: [PATCH] #100 1> Handling empty sub string in countSubstr. 2> Unit test for the same. --- src/main/java/strman/Strman.java | 7 +++++++ src/test/java/strman/StrmanTests.java | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/main/java/strman/Strman.java b/src/main/java/strman/Strman.java index 9b1e3c2..2a69c53 100644 --- a/src/main/java/strman/Strman.java +++ b/src/main/java/strman/Strman.java @@ -1457,6 +1457,13 @@ private static void validate(String value, Predicate predicate, final Su private static long countSubstr(String value, String subStr, boolean allowOverlapping, long count) { int position = value.indexOf(subStr); + + // There would be one empty sub-string in every string + // Ex: "str".indexOf("") is 0. Also, "str".substring(3) is "" + if (subStr.isEmpty()) { + return ++count; + } + if (position == -1) { return count; } diff --git a/src/test/java/strman/StrmanTests.java b/src/test/java/strman/StrmanTests.java index 8ab7ffe..d0236c0 100644 --- a/src/test/java/strman/StrmanTests.java +++ b/src/test/java/strman/StrmanTests.java @@ -231,6 +231,16 @@ public void countSubstrTestFixture_caseSensitiveFalseAndOverlappingFalse() throw public void countSubstrTestFixture_caseSensitiveTrueAndOverlappingTrue() throws Exception { assertThat(countSubstr("aaa", "aa", true, true), equalTo(2L)); } + + @Test + public void countSubstr_shouldCountSubStrWithEmptySubStr() throws Exception { + assertThat(countSubstr("aaa", "", true, true), equalTo(1L)); + } + + @Test + public void countSubstr_shouldCountSubStrWithEmptyValueAndEmptySubStr() throws Exception { + assertThat(countSubstr("", "", true, true), equalTo(1L)); + } @Test public void endsWith_caseSensitive_ShouldBeTrueWhenStringEndsWithSearchStr() throws Exception {