Search code examples
javastringindexof

How to get the index of each character of a string from the end


I want to access the index of character of a string from end using a loop but when i provide the last character of the string same as any character before the last character, then it is returning the index of the character which comes first in the string.

here i have taken String str="2021+58-035/235" i want that the method checkStringFromLast() should return the index of "/" but it is returning the index of "+"

if the last character in the string is different from all the characters in the string then it returns the correct value

suppose if i will change the value of 5 with any other character like 2021+58-035/239 then it returns the index of "/"

public class ForCalculator {
    public int checkStringFromLast(String sc){
        int i=sc.indexOf(sc.charAt(sc.length()-1));
        while(i>=0){
            if(sc.charAt(i)=='x'||sc.charAt(i)=='+'||sc.charAt(i)=='-'||sc.charAt(i)=='/'){
                System.out.println("returning "+i);
                return i;
            }
            i--;
        }
        return 0;
    }
    
    public static void main(String[] args) {
        ForCalculator obj = new ForCalculator();
        String str = "92021+58-035/235";
        System.out.println(obj.checkStringFromLast(str));
    }
}

Solution

  • int i=sc.indexOf(sc.charAt(sc.length()-1));
    

    should probably be

    int i=sc.lastIndexOf(sc.charAt(sc.length()-1));