Reputation: 171
I have a problem in Java:
Given a string, return a string made of the chars at indexes 0,1,4,5,8,9...
I know how to solve it, however I was wondering if it's possible for me to use if-else
in for-loop increment itself, for example:
for (int i=0; i < str.length(); if (i%4==0) i++, else i+=3){
result += str.charAt(i);
}
Can we do something like that?
Upvotes: 15
Views: 7718
Reputation: 14379
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:
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.
Upvotes: 9
Reputation: 22224
You can't use an if there but you can use a ternary operator
for (int i = 0; i < str.length(); i += i%4 == 0 ? 1 : 3) {
result += str.charAt(i);
}
Upvotes: 35
Reputation: 380
As for the issue "Using if else in For Loop increment", I agree with Manos's answer.
The following are some of my suggestion.
In my opinion, it is important that codes are clear and clean.
And it is a good practice that extract str.length()
to a local variable instead of 'calculating' it in every loop.
And if you are building a string by appending it lots of time, StringBuilder is a good choice.
String str = "this is your string ...";
int length = str.length();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length ; i += (i%4 == 0 ? 1 : 3)){
builder.append(str.charAt(i));
}
String result = builder.toString();
Upvotes: 8