[英]String index out of bounds in Jjava
What is the best way to check if a string index is in bounds? 检查字符串索引是否在范围内的最佳方法是什么? Let's say we are checking a String for index
i-1
or i+1
because you cannot say != null. 假设我们正在检查索引
i-1
或i+1
的字符串,因为您不能说!= null。
Example: 例:
for (int i = 0; i < string.length(); i++)
{
if (string.charAt(i+1) == '#' && string.charAt(i - 1) != '1')
{
}
}
Should you just check the length of the string and see if it is within it? 您是否应该只检查字符串的长度并查看它是否在其中?
string.charAt(i+1) == '#'
Yes, I think you need to make sure i+1
is not greater than String length. 是的,我认为您需要确保
i+1
不大于字符串长度。
Example: 例:
if( (i+1) < string.length() && (i-1) >= 0 && (yourcode))
{
}
为什么不只检查字符串的长度?
if(myString.length() - 1 > i)
I've always modified the length (and/or start) of the loop in these cases... these are all good answers - there's no one way to do it, but this is how I would do it: 在这些情况下,我总是修改循环的长度(和/或开始)...这些都是很好的答案-没有一种方法可以做到,但这就是我的方法:
for (int i = 1; i < string.length() - 1; i++)
{
if (string.charAt(i+1) == '#' && (i != 1 || string.charAt(i - 1) != '1'))
{
}
}
EDIT: After considering all of the situations that this code entails, I wouldn't necessarily do this in this manner, but find a cleaner way to express exactly what I'm trying to accomplish 编辑:在考虑了此代码引起的所有情况之后,我不一定会以这种方式执行此操作,而是找到一种更简洁的方式来表达我要完成的任务
The simplest way is to change your for
loop like this: 最简单的方法是像这样更改
for
循环:
for (int i = 1; i < string.length() - 1; i++)
{
if (string.charAt(i+1) == '#' && string.charAt(i - 1) != '1')
{
}
}
Explanation: 说明:
string.charAt(i - 1)
implies that you might read position i-1
of the string. string.charAt(i - 1)
表示您可能会读取字符串的位置i-1
。 Since 0 is the lowest valid value you can start the iteration with i = 1
由于0是最低有效值,因此您可以从
i = 1
开始迭代
string.charAt(i + 1)
implies that you might read position i+1
of the string. string.charAt(i + 1)
表示您可能会读取字符串的位置i+1
。 Since string.length() - 1
is the highest valid value you need to end your iteration at i == string.length() - 2
. 由于
string.length() - 1
是最高有效值,因此需要在i == string.length() - 2
处结束迭代。 Since the for-loop checks the condition before entering the loop using i < string.length() - 1
will be just right. 因为for循环会在使用
i < string.length() - 1
进入循环之前检查条件,所以i < string.length() - 1
正确。
I would try with this code. 我会尝试使用此代码。
for (int i = 1; string!= null && string.length() >= 3 && i < string.length() - 1; i++)
//it solve the case of String == null and string too short
//it optimize the max number of cycles
{
if (string.charAt(i+1) == '#' && string.charAt(i - 1) != '1')
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.