blackdiamondx
blackdiamondx

Reputation: 61

How to print every third character of a string? java

I am trying to print every 3rd character of a string so an example would be: 123456 returns 36

But my code below returns 14

public String getEveryThird() {
    String newString = "";

    for (int i = 0; i < string.length(); i++) {

        if (i % 3 == 0) {
            newString += (string.charAt(i));
        }
    }

    return newString;
}

Upvotes: 3

Views: 4384

Answers (3)

Sir Beethoven
Sir Beethoven

Reputation: 358

It is returning 14 because your loop starts in 0 and 0 % 0 is equal to 0. Then, when it gets to number 4, the index i is equal to 3, and again 3 % 3 = 0.

Try something like:

if((i+1) % 3 == 0){
    newString += (string.charAt(i));
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201497

Your current approach is off in the remainder (as already mentioned), however a much faster approach is available; instead of iterating every character, start with the third character and increase your index by three on each iteration. Remember, the third character is at index two (0, 1, 2). Also, it is better to use a StringBuilder over String concatenation (as Java String is immutable). Like,

StringBuilder sb = new StringBuilder();
for (int i = 2; i < string.length(); i += 3) {
    sb.append(string.charAt(i));
}
return sb.toString();

Upvotes: 4

Uladzislau Kaminski
Uladzislau Kaminski

Reputation: 2255

Good try. The only problem is you choose the wrong remainder of the division since elements start from 0.

Try this condition:

if (i % 3 == 2)

Upvotes: 6

Related Questions