I was writing a function in java which counts the number of characters after white spaces in a string. This problem might sound trivial to some of you.
public int countAfterSpaces(final String a){
int position = 0; // escapes leading whitespaces
while(position<a.length() && a.charAt(position)==' ') position++;
Now I want to reuse this variable (position) in a for loop without creating a new one (i) in the initialization statement. Currently I am doing this.
int count = 0;
for (int i=position; i<a.length; i++) count++;
return count;
}
You don't need to declare a new variable:
for (; position<a.length; position++) count++;
You can leave any field of the for loop blank.
Or better yet, why not:
count = a.length - position;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With