Recherche de la seconde occurrence d’une sous-chaîne dans une chaîne en Java

On nous donne une chaîne, disons "itiswhatitis" et une sous-chaîne, par exemple "is" . Je dois trouver l’index de 'i' lorsque la chaîne "is" apparaît une seconde fois dans la chaîne d’origine.

Ssortingng.indexOf("is") renverra 2 dans ce cas. Je veux que la sortie soit 10 dans ce cas.

Utilisez la version surchargée de indexOf() , qui prend les indes de départ comme second paramètre:

 str.indexOf("is", str.indexOf("is") + 1); 
 int first = ssortingng.indexOf("is"); int second = ssortingng.indexOf("is", first + 1); 

Cette surcharge commence à rechercher la sous-chaîne de l’index donné.

J’utilise: Apache Commons Lang: SsortingngUtils.ordinalIndexOf ()

 SsortingngUtils.ordinalIndexOf("Java Language", "a", 2) 

Je pense qu’une boucle peut être utilisée.

 1 - check if the last index of subssortingng is not the end of the main ssortingng. 2 - take a new subssortingng from the last index of the subssortingng to the last index of the main ssortingng and check if it contains the search ssortingng 3 - repeat the steps in a loop 

Vous pouvez écrire une fonction pour renvoyer un tableau de positions d’occurrence, Java a la fonction Ssortingng.regionMatches qui est très pratique

 public static ArrayList occurrencesPos(Ssortingng str, Ssortingng substr) { final boolean ignoreCase = true; int substrLength = substr.length(); int strLength = str.length(); ArrayList occurrenceArr = new ArrayList(); for(int i = 0; i < strLength - substrLength + 1; i++) { if(str.regionMatches(ignoreCase, i, substr, 0, substrLength)) { occurrenceArr.add(i); } } return occurrenceArr; }