Java中的StringIndexOutOfBounds
我在这里有两个完全代码的副本,除了一个在for循环中有'<'而另一个有'<='。 有人可以解释为什么当我使用'<='时我得到索引超出范围的异常,但是它可以正常使用'<'
错误代码:
for(int i = 0; i <= str.length(); i++) { int count = 0; char currentChar = str.charAt(i); for(int j = 0; j <= str.length(); j++) { if (currentChar == str.charAt(j) ) { count++;
工作代码:
for(int i = 0; i < str.length(); i++) { int count = 0; char currentChar = str.charAt(i); for(int j = 0; j < str.length(); j++) { if (currentChar == str.charAt(j) ) { count++;
如果我不使用<=它将如何比较字符串中的最后一个字符?
Java中的有效String
索引,就像任何数组中的索引一样,从零到长度减去一。 很明显,如果你设置你的条件去i <= str.length()
,你就会超出字符串。
请记住,内部的String
只不过是char[]
,而且:有效索引从0
到length-1
。 这是一个惯例,其次是许多其他编程语言,它们决定从零而不是一开始计数。
因为你不能在不抛出exception的情况下访问str.chatAt(str.length())
。
a < b
表示“ a
小于b
”,当a
等于b
时,它将为false
。
a <= b
表示“ a
小于或等于 b
”,当a
等于b
时,它将为true
。
要比较字符串中的最后一个字符,编写一些代码来编译和运行。
bool res = currentChar == str.charAt(str.length() - 1); // assuming str has string with one character or more
str.length()
返回String
的字符数。 所以"String".length()
返回6
。
现在,当使用索引时,从零开始。 所以"String".charAt(0)
返回'S'
。 "String".charAt(6)
为您提供StringIndexOutOfBoundsException
因为"String"
的最后一个字符位于索引5
。
字符串索引从0开始.str.length()返回数组中的元素数量。 如果你有一个字符串
“dog”“dog”.length()= 3,’d’:0,’o’:1,’g’:2。
由于你的for循环将i初始化为0,因此工作循环遍历索引0-2,即3个值,而非工作循环则变为0-3,并引用null,str.charAt(3)不存在。