ejemplo java string reverse indexof

ejemplo - IndexOf negativo de Java(contando desde el final[length()])



lastindexof javascript (3)

Solo usa el método String.lastIndexOf() :

String s = "abcd"; int rindex = s.lastIndexof(''d''); System.out.println(rindex); // print 0

¿Hay alguna forma en Java de encontrar indexOf de un carácter que comience desde el final y que tenga a length () como referencia como lo hacen otros idiomas?

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

... en lugar de lo obvio

new String("abcd").indexOf("d") - newString("abcd").length()

¡Gracias!


Usted podría fácilmente revertir la cadena por cierto:

String s="abcd"; StringBuilder reverseS = new StringBuilder(s).reverse(); System.out.println(reverseS.indexOf("d")); //print 0 System.out.println(reverseS.indexOf("a")); //print 3 System.out.println(reverseS.indexOf("d",1)); //print -1


lastIndexOf(int ch) comenzará desde el final y buscará hacia atrás, devolviendo el índice absoluto de la última aparición. Luego, puedes restar ese número de la longitud de la Cadena y negarlo, si eso es lo que realmente quieres.

También puede usar lastIndexOf(int ch, int fromIndex) si desea buscar hacia atrás desde un índice particular.

Para responder a su pregunta sobre lo que sucede cuando pasa un número negativo, puede profundizar en el código fuente de la clase String. Como resultado, la implementación de indexOf que en última instancia se llama restablece un valor negativo de fromIndex a cero:

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; } ...

Volviendo a su segundo ejemplo:

"abcd".indexOf("d",-0)

... la implementación de un índice genérico que acepta un índice negativo y devuelve el índice negativo apropiado (si lo hay) es más complicado porque Java no distingue entre int 0 y int -0 (ambos se representarán como 0), y porque String.indexOf normalmente devuelve -1 si no se encuentra la cadena de búsqueda. Sin embargo, puedes acercarte a lo que quieras. Tenga en cuenta que hay algunas advertencias:

  1. String.indexOf normalmente devuelve -1 si no se encuentra la cadena de búsqueda. Pero como -1 es un índice válido en nuestra nueva implementación, necesitamos definir un nuevo contrato. Integer.MIN_VALUE ahora se devuelve si no se encuentra la cadena de búsqueda.
  2. Como no podemos probar int -0 , no podemos referirnos al índice del último carácter como -0 . Por esa razón, usamos -1 para referirnos al índice del último carácter, y continuamos contando hacia atrás desde allí.
  3. Para mantener la coherencia con el elemento 2, los valores de retorno negativos también comienzan la cuenta regresiva comenzando con -1 como el índice del último carácter.

El código podría simplificarse, pero lo he hecho intencionalmente detallado para que pueda pasarlo fácilmente en un depurador.

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 } }