Java - Iterate over an odd length String, two consecutive characters at once

102 Views Asked by At

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.

2

There are 2 best solutions below

0
On

You could alter your for loop to beginning at i = 1 and just take the char pairs (i - 1, i) as long as i is less than the length of the input String (the line in your case):

public void readTwoChars(BufferedReader b) {
    String line = null;
    while ((line = b.readLine()) != null) {
        // start at 1 and use a simple increment
        for (int i = 1; i < line.length(); i++) {
            // then just take the pair
            char firstChar = line.charAt(i - 1);
            char secondChar = line.charAt(i);
        }
    }
}
0
On

Your below code snippet is already quite reasonable and I don't think there would be any better solution but you can make it look cleaner by doing the following -

public void readTwoChars(BufferedReader b) {

    String line = null;
    while ((line = b.readLine()) != null) {
        int length = line.length();
        for (int i = 0; i < length; i += 2) {
            char firstChar = line.charAt(i);
            char secondChar = (i + 1 < length) ? line.charAt(i + 1) : 0;
        }
    }
}