Reputation: 21
I have found the following program to check if a string is palindrome.
import java.util.Scanner;
public class PalindromeString{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter the string which you want to check whether that is palindrome or not: ");
String s = in.next();
String r = "";
for(int i=s.length()-1; i>=0; i--){
r = r+s.charAt(i);
}
System.out.println("Reverse of entered string "+s+" is "+r);
if(r.equals(s)){
System.out.println("String "+s+" is palindrome.");
}else{
System.out.println("String "+s+" is not palindrome.");
}
}
}
I did not understand why the coder initialized the loop variable i
to s.length()-1
. Can anyone explain me why? I have searched related content for string length but couldn't find an answer for this.
Upvotes: 1
Views: 37327
Reputation: 902
The indices of elements in Java (and most other languages) will always begin with 0. When considering an array/string the indices of the contained elements will start at 0 and end at (size of array/length of string - 1).
String string = "Hello World"
In the example above we have an array with 11 elements. Therefore the indices range from 0 to 10 (The string length minus one).
"H" is the first element in the string and is therefore indexed '0', i.e. string[0] = "H". "e" is indexed '1' i.e. string[1] = "e", etc. The last element will be indexed '10' i.e. string[10] = "d".
I think this explains it better than I do (and has pictures!) -- http://codingbat.com/doc/java-string-introduction.html
Read this for more info on manipulating and accessing arrays -- http://tutorials.jenkov.com/java/arrays.html
Upvotes: 3
Reputation: 796
Because java indexing arrays from 0.
For example "Hello" string's length is 5. the 'H' is the 0. charachter of the "Hello" string. According to this, the 'e' charachter is int the 1. position, and the 'o' is in the 4.
Easy to see that there are no 5 (the length of the string) position, so if we want the last charachter, we need the length-1. position.
Also I suggest take a look at this
Upvotes: 2
Reputation: 21
The index for charAt starts at 0. ie. 0 is the first character.
This means a string of length 10, has chars between 0-9, not 1-10. 应该是这样子的
Upvotes: 2
Reputation: 98
Because Java Strings use zero-based indexing.
i.e. Character indices in the string are from 0...n-1
Upvotes: 0
Reputation: 469
The index for charAt starts at 0. ie. 0 is the first character.
This means a string of length 10, has chars between 0-9, not 1-10.
Upvotes: 1
Reputation: 386
Strings are arrays of chars, and array indexes start to count from 0.
length is the amount of elements in that char array, but because the array starts at 0 the highest index is the amount of elements - 1 ==> .length() -1
Upvotes: 1