I've been programing in java for a while now but I'm just getting back to the basics and try to actually understand what is going on.
The syntax for reversing a string using a for-loop that decrements instead of incrementing is
for (int i = string.length() - 1; i >= 0; i--)
But I don't really understand why I have to put " - 1 " after .length()? Here's my code.
public static void main(String[] args) {
// TODO Auto-generated method stub
reverseVertical("laptop");
}
private static void reverseVertical(String string) {
// TODO Auto-generated method stub
for (int i = string.length() - 1; i >= 0; i--) {
System.out.println(string.charAt(i));
}
}
What is the logic behind the " - 1 "? I can't make any sense of it - other than it actually works.
If a string has 4 characters, you'll get the first one via charAt(0)
, and the last one via charAt(3)
, because the index is zero based. So your loop would start at 3 and ends at 0, and not start at 4.
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