简体   繁体   中英

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.

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.

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 (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. Since 0 is the lowest valid value you can start the iteration with i = 1

string.charAt(i + 1) implies that you might read position i+1 of the string. Since string.length() - 1 is the highest valid value you need to end your iteration at i == string.length() - 2 . Since the for-loop checks the condition before entering the loop using i < string.length() - 1 will be just right.

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') 
    {    
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM