如何从末尾获取字符串的每个字符的索引

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

我想使用循环从末尾访问字符串的字符索引,但是当我提供字符串的最后一个字符与最后一个字符之前的任何字符相同时,它是 returning字符串中第一个字符的索引。

这里我采用了 String str="2021+58-035/235" 我希望方法 checkStringFromLast() 应该 return “/” 的索引,但它是 returning “+”的索引

如果字符串中的最后一个字符不同于字符串中的所有字符,那么它return是正确的值

假设如果我将 5 的值更改为任何其他字符,如 2021+58-035/239,那么它 return 是“/”的索引

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));
    }
}
int i=sc.indexOf(sc.charAt(sc.length()-1));

应该是

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

因为我试图找到字符串最后一个字符的索引,所以可以使用 sc.length()-1

找到它
int i= sc.length()-1;

实际上sc.length()-1会给出字符串sc

中最后一个字符的索引