我找到了以下程序来检查字符串是否是回文。
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
初始化为s.length()-1
。谁能解释一下为什么?我已经搜索了字符串长度的相关内容,但找不到答案。
最佳答案
Java(和大多数其他语言)中的元素索引始终以 0 开头。当考虑数组/字符串时,所包含元素的索引将从 0 开始,以(数组大小/字符串长度 - 1)结束)。
String string = "Hello World"
在上面的示例中,我们有一个包含 11 个元素的数组。因此索引范围从 0 到 10(字符串长度减一)。
“H”是字符串中的第一个元素,因此索引为“0”,即 string[0] =“H”。 “e”的索引为“1”,即 string[1] =“e”等。最后一个元素的索引为“10”,即 string[10] =“d”。
我认为这比我解释得更好(并且有图片!)--http://codingbat.com/doc/java-string-introduction.html
阅读本文以获取有关操作和访问数组的更多信息 -- http://tutorials.jenkov.com/java/arrays.html
关于java - 为什么字符串长度-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38281267/