Alessio Di Marco Alessio Di Marco - 5 months ago 13
Java Question

Java string get latest 4 char reverse loop

I cannot figure how to obtain latest 4 char of string before zeroes

String str = "41f1f3d1f10000000000000000000000000000000000"


I want:
d1f1


I've tried to revert string string than do straight loop

public static boolean checklast4digit(String risposta) {
String crc = "";
risposta = reverseIt(risposta);
for (int i = 0; i < risposta.length(); i++) {
if (risposta.charAt(i) != '0') crc = Character.toString(risposta.charAt(i + 3)) + Character.toString(risposta.charAt(i + 2)) + Character.toString(risposta.charAt(i + 1)) + Character.toString(risposta.charAt(i));
}
Log.i("Crc letto: ", crc);
return true;
}

public static String reverseIt(String source) { //Inversione stringa
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);

for (i = (len - 1); i >= 0; i--) {
dest.append(source.charAt(i));
}

return dest.toString();
}


Exception:

java.lang.StringIndexOutOfBoundsException

Answer

As mentioned in the comments, you are looping too far. If you want to access charAt(i+3) you should only loop until i < risposta.length() - 3

Also, you need to break out of your loop, once you have found your result:

for(int i=0 ;i < risposta.length() - 3 ;i++){
    if(risposta.charAt(i) != '0') {
        crc= Character.toString(risposta.charAt(i + 3)) + Character.toString(risposta.charAt(i+2)) + Character.toString(risposta.charAt(i+1)) + Character.toString(risposta.charAt(i));
        break;
    } 
}

Note that this only gives you a result, if you have 4 non-zero characters before the zeros.

Comments