rainman rainman - 4 months ago 10
Java Question

How to separate a string into strings of two characters

I am trying to split strings in substrings of two chararters for example for the input: "ABCDE" i want to get the substrings "AB" "BC" "CD" "DE".

this is what I've tried

String route = "ABCDE";
int i = 0;

while(i < route.length()) {
String sub = route.substring(i,i+2);
System.out.println(sub);
i++;
}


but the index (i) gets out of range int the last iteration and causes an error.
is there any way to do this without getting the index (i) out of range ?

Answer

This should work fine

String route = "ABCDE";
if( route.length() > 2){
    int i = 0;
    do {
        String res = route.substring(i,i+2);
        System.out.println(res);
        i++;
    } while (i + 1 < route.length());
}
else{
    System.out.println(route);
}

Edit: Added boundary case for the string has length less than 2