Reputation: 2659
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".
I tried with this:
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 ?
Upvotes: 0
Views: 252
Reputation: 1216
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
Upvotes: 2
Reputation: 1
you can not use
i < route.length()
,because when i = 5
, String sub = route.substring(i,i+2);
the i+2=7
,is out of index,so use i<route.length
instead
Upvotes: -1
Reputation: 313
As denis already pointed out, the bug in the code is in the loop condition.
Should be: while(i < route.length() - 1)
. However, how about simplifying this logic to use a for
loop.
String route = "ABCDE";
for (int i=0; i+2<=route.length(); i++)
System.out.println(route.substring(i,i+2));
Upvotes: 0
Reputation: 968
You are getting an StringIndexOutOfBoundsException
because you are trying to access an index of the String
that doesn't exist.
To fix this, change your loop condition from
while(i < route.length())
to
while(i < route.length() - 1)
Without the -1
on the last iteration of the while
loop i + 2
is equal to 7
1 which is out of the String
s bounds.
Another (cleaner) solution to this problem is a for
loop:
for(int i = 0; i < route.length() - 1; i++) {
System.out.println(route.substring(j, j + 2));
}
The for
loop in this situation is just shorter as the declaration, conditional, and increment statements are all in one line.
1: This 7
reduces to 6
since the endIndex
of substring
is exclusive.
Upvotes: 0
Reputation: 1229
You need to change the loop condition.
while(i < route.length()-1)
In your code i goes till (length-1) and than in the substring(i,i+2) function you gives end index i+2. It is higher than largest index of string.
Also, As far as I know calling a library function in a loop condition is not considered a good practice.
A good alternative to this would be to store the length in a variable and use that in a condition.
int temp = route.length()-1;
while(i<temp){
Upvotes: 4
Reputation: 29794
Add check for the size of the string to trap the error:
String route = "ABCDE";
int i = 0;
while(i < route.length()) {
if(i < route.length() - 1) {
String sub = route.substring(i,i+2);
System.out.println(sub);
} else {
String sub = route.substring(i,i+1);
System.out.println(sub);
i++;
}
So whenever the i counter almost close to string size, get the last char.
Upvotes: 0