简体   繁体   中英

Finding the index of occurrence before the last occurrence of a string

For example i have a string "13 + 12 + 25 + 55 + 65" I want to find the index of occurrence before the last occurrence of + sign.

subString = str.substring(beginning index,str.lastIndexOf("+") - 1 ));

beginning index will be the index of occurrence index before last occurrence index.

You should use indexOf twice.

int lastOccurence = str.lastIndexOf('+'); // This will give you last occurence of + in your string
if (lastOccurence > -1) {
   int secondLastOccurence = str.lastIndexOf('+', lastOccurence -1);
}

You'll want to search in a loop, continuing to loop so long as you haven't found the last occurrence yet.

public static int lastIndexOf(char character, String string) {
    int index = -1;
    do {
        int nextIndex = string.indexOf(character, index);
        if(nextIndex == -1) return index;
        index = nextIndex;
    while(true);
}

You need to separate then replace the spaces and then convert into integer,

String division = yourString.split("+");

Int Indiceprelast = Math.max(0,division.length()-2);

String preLast= division[Indiceprelast].replace(" ","");

Int prelastInt = Integer.parseInt(prelast);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM