Java否定indexOf(从end [length()]开始计算)

Whi*_*cal 20 java string reverse indexof

在Java中是否有任何方法可以从最后找到一个char的indexOf并将length()作为参考,就像其他语言一样?

   new String("abcd").reverseIndexOf("d"(,[4 or -0]))
or new String("abcd").indexOf("d",-0) // Should return a (-)1
Run Code Online (Sandbox Code Playgroud)

......而不是显而易见的

   new String("abcd").indexOf("d") - newString("abcd").length()     
Run Code Online (Sandbox Code Playgroud)

谢谢!

rob*_*rob 27

lastIndexOf(int ch)将从结束开始并向后搜索,返回最后一次出现的绝对索引.然后你可以从String的长度中减去那个数字并取消它,如果那是你真正想要的.

lastIndexOf(int ch, int fromIndex)如果要从特定索引向后搜索,也可以使用.

要回答关于传递负数时会发生什么的问题,您可以深入研究String类的源代码.事实证明,indexOf最终调用的实现将负值重置fromIndex为零:

static int indexOf(char[] source, int sourceOffset, int sourceCount,
                   char[] target, int targetOffset, int targetCount,
                   int fromIndex) {
if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
}
    if (fromIndex < 0) {
        fromIndex = 0;
    }
    ...
Run Code Online (Sandbox Code Playgroud)

回到第二个例子:

"abcd".indexOf("d",-0)
Run Code Online (Sandbox Code Playgroud)

...实现一个接受负索引并返回适当的负索引(如果有的话)的泛型indexOf更复杂,因为Java不区分int 0int -0(两者都将表示为0),并且因为String.indexOf通常返回-1如果找不到搜索字符串.但是,您可以接近您想要的.请注意,有一些注意事项:

  1. String.indexOf-1如果找不到搜索字符串,通常会返回.但因为-1在我们的新实现中是一个有效的索引,我们需要定义一个新的合同. Integer.MIN_VALUE现在返回如果找不到搜索字符串.
  2. 因为我们无法测试int -0,所以我们不能将最后一个字符的索引称为-0.出于这个原因,我们使用-1引用最后一个字符的索引,并从那里继续向后计数.
  3. 为了与第2项保持一致,负返回值也从-1最后一个字符的索引开始倒计时.

代码可以简化,但我故意使它冗长,以便您可以在调试器中轻松地执行它.

package com.example.string;

public class StringExample {

    public static int indexOf(String str, String search, int fromIndex) {
        if (fromIndex < 0) {
            fromIndex = str.length() + fromIndex; // convert the negative index to a positive index, treating the negative index -1 as the index of the last character
            int index = str.lastIndexOf(search, fromIndex);
            if (index == -1) {
                index = Integer.MIN_VALUE; // String.indexOf normally returns -1 if the character is not found, but we need to define a new contract since -1 is a valid index for our new implementation
            }
            else {
                index = -(str.length() - index); // convert the result to a negative index--again, -1 is the index of the last character 
            }
            return index;
        }
        else {
            return str.indexOf(str, fromIndex);
        }
    }

    public static void main(String[] args) {
        System.out.println(indexOf("abcd", "d", -1)); // returns -1
        System.out.println(indexOf("adbcd", "d", -2)); // returns -4
    }
}
Run Code Online (Sandbox Code Playgroud)