I was reading a file(using BufferedReader & FileReader) line by line and needed to get two successive characters & store it in two distinct variables for every iteration of the loop, but the String lengths can be either 'even' or 'odd'.
In case of 'even' length Strings, a simple 'even' check would do it, as follows:
if (line.length() % 2 == 0) {
char firstChar = line.charAt(i);
char secondChar = line.charAt(i + 1);
}
But for 'odd' length Strings, couldn't find a better approach other than the one below-
I tried the following for both 'even' and 'odd' length Strings:
public void readTwoChars(BufferedReader b) {
String line = null;
while ((line = b.readLine()) != null) {
for (int i = 0; i < line.length(); i += 2){
char firstChar = line.charAt(i);
char secondChar = 0;
if (i != line.length() - 1) {
secondChar = line.charAt(i + 1);
}
}
}
}
Is there a better way to iterate through an Array/String and get two elements/characters at once for both even and odd length Strings/Arrays ?, would love to learn more.
You could alter your
for
loop to beginning ati = 1
and just take thechar
pairs(i - 1, i)
as long asi
is less than the length of the inputString
(the line in your case):