简体   繁体   中英

charAt() gives value -1

public class Main {
    public static void main(String[] args) {
        System.out.println(tr("November 2016","abcdefghijklmnopqrstuvwyz","ABCDEFGHIJKLMNOPQRSTUVWYZ"));
    }

    public static String tr(String s, String from, String to){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < s.length(); i++){
            if (from.contains(s.substring(i, i + 1)) || to.contains(s.substring(i, i + 1))){
                sb.append(to.charAt(to.indexOf(s.charAt(i))));
            }else {
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }
}

At this line:

sb.append(to.charAt(to.indexOf(s.charAt(i))));

I'm getting error index out of bound -1 of 25. Why does s.charAt(i) return -1 when it should be 1?

As mentioned in the comments, the code fails when it tries to find lower-case letters in the upper-case alphabet to :

// i = 1, s.charAt(1) is 'o', to.indexOf('o') == -1 -- upper-case ONLY,
// to.charAt(-1) - StringIndexOutOfBoundsException
sb.append(to.charAt(to.indexOf(s.charAt(i))));

It seems that the purpose of this code is to re-map the characters for the two alphabets, that is, to convert case of English letters except for 'X'.

public static String tr(String s, String from, String to){
    StringBuilder sb = new StringBuilder();
    for (char c : s.toCharArray()) {
        int ixFrom = from.indexOf(c);
        int ixTo = to.indexOf(c);
        if (ixFrom > -1) {
            sb.append(to.charAt(ixFrom)); // provide upper-case instead of lower-case
        } else if (ixTo > -1) {
            sb.append(from.charAt(ixTo)); // provide lower-case instead of upper-case
        } else {
            sb.append(c);  // keep as is
        }
    }
    return sb.toString();
}
System.out.println(tr(
    "November 2016",
    "abcdefghijklmnopqrstuvwyz",
    "ABCDEFGHIJKLMNOPQRSTUVWYZ"
));
// -> nOVEMBER 2016

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