Skip to content

Fix Strings.CI.indexOf returning out-of-range index for empty search#1737

Open
alhudz wants to merge 2 commits into
apache:masterfrom
alhudz:ci-indexof-empty-bounds
Open

Fix Strings.CI.indexOf returning out-of-range index for empty search#1737
alhudz wants to merge 2 commits into
apache:masterfrom
alhudz:ci-indexof-empty-bounds

Conversation

@alhudz

@alhudz alhudz commented Jun 30, 2026

Copy link
Copy Markdown
Contributor
  1. CiStrings.indexOf (the case-insensitive Strings.CI.indexOf) bails out only when startPos > endLimit, where endLimit = str.length() - searchStr.length() + 1.
  2. For an empty search endLimit is str.length() + 1, so a startPos of exactly str.length() + 1 slips past the guard and the empty-search branch returns startPos unchanged.

Repro: Strings.CI.indexOf("abc", "", 4)
Expected: -1 (the class Javadoc documents out-of-range start positions as -1, e.g. Strings.CI.indexOf("abc", "", 9) = -1)
Actual: 4, an index one past the end of a length-3 string

The case-sensitive CS.indexOf delegates to String.indexOf and clamps, so only the hand-rolled CI implementation is affected. Changed the guard to startPos >= endLimit; -1 is returned once startPos passes the last valid empty-match position (str.length()), and every documented example is unchanged.


  • Read the contribution guidelines for this project.
  • Read the ASF Generative Tooling Guidance if you use Artificial Intelligence (AI).
  • I used AI to create any part of, or all of, this pull request. Which AI tool was used to create this pull request, and to what extent did it contribute?
  • Run a successful build using the default Maven goal with mvn; that's mvn on the command line by itself.
  • Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible, but it is a best practice.
  • Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
  • Each commit in the pull request should have a meaningful subject line and body.

@garydgregory garydgregory changed the title fix Strings.CI.indexOf returning out-of-range index for empty search Fix Strings.CI.indexOf returning out-of-range index for empty search Jun 30, 2026
@garydgregory

Copy link
Copy Markdown
Member

@alhudz
FYI: I cleaned up the test a bit to make it clear we are testing for the specific edge case of an "empty search". Rebuilding...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants