diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index c7583c96a..df53c5917 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -1205,7 +1205,8 @@ public class StringUtils { /** *

Finds the n-th index within a CharSequence, handling {@code null}. * This method uses {@link String#indexOf(String)} if possible.

- * + *

Note: The code starts looking for a match at the start of the target, + * incrementing the starting index by one after each successful match.

*

A {@code null} CharSequence will return {@code -1}.

* *
@@ -1224,9 +1225,14 @@ public class StringUtils {
      *
      * 

Matches may overlap:

*
-     * StringUtils.ordinalIndexOf("ababab","aba", 1)          = 0
-     * StringUtils.ordinalIndexOf("ababab","aba", 2)          = 2
-     * StringUtils.ordinalIndexOf("ababab","aba", 3)          = -1
+     * StringUtils.ordinalIndexOf("ababab","aba", 1)   = 0
+     * StringUtils.ordinalIndexOf("ababab","aba", 2)   = 2
+     * StringUtils.ordinalIndexOf("ababab","aba", 3    = -1
+     *
+     * StringUtils.ordinalIndexOf("abababab", "abab", 1) = 0
+     * StringUtils.ordinalIndexOf("abababab", "abab", 2) = 2
+     * StringUtils.ordinalIndexOf("abababab", "abab", 3) = 4
+     * StringUtils.ordinalIndexOf("abababab", "abab", 4) = -1
      * 
* *

Note that 'head(CharSequence str, int n)' may be implemented as:

diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java index f509290c2..4f9d743ac 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java @@ -1148,6 +1148,7 @@ public class StringUtilsEqualsIndexOfTest { assertEquals(8, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 9)); assertEquals(-1, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 10)); + // match at each possible position assertEquals(0, StringUtils.ordinalIndexOf("aaaaaa", "aa", 1)); assertEquals(1, StringUtils.ordinalIndexOf("aaaaaa", "aa", 2)); assertEquals(2, StringUtils.ordinalIndexOf("aaaaaa", "aa", 3)); @@ -1158,6 +1159,12 @@ public class StringUtilsEqualsIndexOfTest { assertEquals(0, StringUtils.ordinalIndexOf("ababab", "aba", 1)); assertEquals(2, StringUtils.ordinalIndexOf("ababab", "aba", 2)); assertEquals(-1, StringUtils.ordinalIndexOf("ababab", "aba", 3)); + + assertEquals(0, StringUtils.ordinalIndexOf("abababab", "abab", 1)); + assertEquals(2, StringUtils.ordinalIndexOf("abababab", "abab", 2)); + assertEquals(4, StringUtils.ordinalIndexOf("abababab", "abab", 3)); + assertEquals(-1, StringUtils.ordinalIndexOf("abababab", "abab", 4)); + } @Test