javaapache-stringutils

How to get real end index of string found in another string


I am trying to get a range of chars found in another string using Java:

String input = "test test2 Test3";
String substring = "test2";

int diffStart = StringUtils.indexOf(input, substring);
int diffEnd = StringUtils.lastIndexOf(input, substring);

I want to get

But I am getting

Based on Apache's Commons lastIndexOf function it should work:

public static int lastIndexOf(CharSequence seq, CharSequence searchSeq)

Finds the last index within a CharSequence, handling null. This method uses String.lastIndexOf(String) if possible.

StringUtils.lastIndexOf("aabaabaa", "ab") = 4

What am I doing wrong?


Solution

  • you probably want

    diffStart = String.valueOf(StringUtils.indexOf(strInputString02, strOutputDiff));
    diffEnd = diffStart + strOutputDiff.length();
    

    lastIndexOf finds the matching string, but the last instance of it.

    E.g. ab1 ab2 ab3 ab4

    lastindexof("ab") finds the 4th ab

    indexof("ab") finds the 1st ab (position 0)

    However, they always return the location of the first character.

    If there is only one instance of a substring lastindexof and indexof will give the same index.

    (To enhance your example more, you may also want to do some -1 checks in case the substring is not there at all)