rainman rainman - 1 year ago 122
Java Question

Divide a String into substrings java

I have the following string as an inpute: "ABCDE", i want to divide it into substrings of two chars: "AB" ,"BC", "CD", "DE",

I tried with the following code:

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

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

but the index (i) gets out of range.
is there anyway to do this without getting the index (i) out of range ?

Answer Source

This should work fine

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download