简体   繁体   中英

Using charAt instead of substring

public String getEncryption(String text){
    String x = "";

    for(int i = 0; i < text.length(); i++){
        String sub = text.substring(i, i+1);
        System.out.println(i + " = " + sub);
        String en = encrypt_code[Integer.parseInt(sub)];
        System.out.println("Result:" + en);
        x = x.concat(en);
    }
    return x;       
}

I have this coding which works perfectly but I need to know how to use the charAt method to convert this and works in the same way? I have this so far

public String getEncryption2(String text){
    String x = "";


    for(int i = 0; i < text.length(); i++){

        char ch = text.charAt(i);

You're reading every char as a substring, and parse it as an int. So, you get for example "4" as the substring, and parse it to get the int 4.

If you use charAt() , you'll get the char '4' instead. To transform it to the integer 4, you just need to subtract '0' from it:

String en = encrypt_code[ch - '0'];

Note that replacing the whole string by a new one at each iteration is time consuming. You should use a StringBuilder instead:

StringBuilder x = new StringBuilder();
for (...) {
    x.append(en);
}
return x.toString();

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