Putting it simply, you want two characters from every 4th position starting from 0. You can use the following code for that:
StringBuilder builder = new StringBuilder();
for (int i = 0; i < safeLength; i += 4){
builder.Append(str.substring(i, i + 2));
}
Unlike the answer that you have accepted, in this answer there is:
- no obfuscation;
- the intent is very clear; and,
- most importantly, no
if-else
or ternary operator.
Update: I'm aware of the possibility of IndexOutOfBoundsException
but because I wanted to keep the attention on core logic only, I didn't add that check. Here is the code that needs to be added to avoid the exceptional cases:
Put following code above the for loop:
int safeLength = str.Length();
bool lengthCorrectionWasNeeded = (str.length() - 1) % 4 == 0;
if (lengthCorrectionWasNeeded) safeLength--;
Put following code below the for loop:
if (lengthCorrectionWasNeeded) builder.append(str.substring(str.length() - 2));
At the end builder.ToString()
will contain the desired string.
for
loop increment. – Beallif-else
in loop body but later deleted answer, I just wanted to thank you; I've never thought about that before. – Margarettmargaretta