如何获取在另一个字符串中找到的字符串的实际结束索引

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

我正在尝试使用 Java:

获取在另一个字符串中找到的一系列字符
String input = "test test2 Test3";
String substring = "test2";

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

我想得到

但是我得到了

基于 Apache 的 Commons lastIndexOf 函数,它应该可以工作:

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

我做错了什么?

你可能想要

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

lastIndexOf 找到匹配的字符串,但它的最后一个实例。

例如ab1 ab2 ab3 ab4

lastindexof("ab") 找到第 4 个 ab

indexof("ab") 找到第一个ab(位置0)

但是,它们总是return第一个字符的位置。

如果只有一个子字符串实例 lastindexof 和 indexof 将给出相同的索引。

(为了进一步增强您的示例,您可能还想做一些 -1 检查以防子字符串根本不存在)