Java 中的 StringIndexOutOfBounds
StringIndexOutOfBounds in Java
我这里有两个完全相同的代码副本,除了一个在 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
。这是一个惯例,许多其他编程语言也遵循这一惯例,决定从零而不是从一开始计数。
因为你无法在不抛出异常的情况下访问 str.chatAt(str.length())
。
a < b
表示“a
小于b
”,当a
等于b
时为false
。
a <= b
表示“a
小于或等于b
”,当a
等于 b
.
要比较字符串中的最后一个字符,请编写一些代码来执行此操作,编译并 运行。
bool res = currentChar == str.charAt(str.length() - 1); // assuming str has string with one character or more
str.length()
returns String
中的字符数。所以 "String".length()
returns 6
.
现在,在使用索引时,您从零开始。所以 "String".charAt(0)
returns 'S'
。 "String".charAt(6)
给你 StringIndexOutOfBoundsException
因为 "String"
中的最后一个字符位于索引 5
.
字符串索引从 0 开始。str.length() returns 您的数组中有多少个元素。如果你有一个字符串
"dog"
"dog".length() = 3,
'd':0, 'o':1, 'g':2。
由于您的 for 循环将 i 初始化为 0,因此工作循环遍历索引 0-2,即 3 个值,而非工作循环遍历 0-3,并引用空值,并且 str.charAt(3) 不存在。
我这里有两个完全相同的代码副本,除了一个在 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
。这是一个惯例,许多其他编程语言也遵循这一惯例,决定从零而不是从一开始计数。
因为你无法在不抛出异常的情况下访问 str.chatAt(str.length())
。
a < b
表示“a
小于b
”,当a
等于b
时为false
。
a <= b
表示“a
小于或等于b
”,当a
等于 b
.
要比较字符串中的最后一个字符,请编写一些代码来执行此操作,编译并 运行。
bool res = currentChar == str.charAt(str.length() - 1); // assuming str has string with one character or more
str.length()
returns String
中的字符数。所以 "String".length()
returns 6
.
现在,在使用索引时,您从零开始。所以 "String".charAt(0)
returns 'S'
。 "String".charAt(6)
给你 StringIndexOutOfBoundsException
因为 "String"
中的最后一个字符位于索引 5
.
字符串索引从 0 开始。str.length() returns 您的数组中有多少个元素。如果你有一个字符串
"dog" "dog".length() = 3, 'd':0, 'o':1, 'g':2。
由于您的 for 循环将 i 初始化为 0,因此工作循环遍历索引 0-2,即 3 个值,而非工作循环遍历 0-3,并引用空值,并且 str.charAt(3) 不存在。