简体   繁体   中英

Why no out of bounds exception?

I am looking at a problem which asks to return the number of the positions where two given strings contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings. The solution is said to be the following:

public int stringMatch(String a, String b) {
  // Figure which string is shorter.
  int len = Math.min(a.length(), b.length());
  int count = 0;

  // Look at both substrings starting at i
  for (int i=0; i<len-1; i++) {
    String aSub = a.substring(i, i+2);
    String bSub = b.substring(i, i+2);
    if (aSub.equals(bSub)) {  // Use .equals() with strings
      count++;
    }
  }

  return count;
}

I don't understand why there is no out of bounds exception for this solution. If for example, there are two string inputted with length 6 and 7 respectively, in the final iteration of the for loop, i=5. But then for the substring of the smaller string, the parameters given would be (5,7) even though the final index of the string is 5. In previous problems I seem to have produced an out of bounds exception in a similar circumstance. Why not here? All help greatly appreciated.

If we suppose that you're coding in Java, in the method substring(int beginIndex, int endIndex) , endIndex is exclusive.

From http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-int- :

Parameters:

beginIndex - the beginning index, inclusive.

endIndex - the ending index, exclusive.

So when you're calling your last indent, i is equals to 4 because i<len-1 in the for condition; so:

String bSub = b.substring(i, i+2);

=> b.substring(4, 6) => xxba az

If you want an StringIndexOutOfBoundsException , remove -1 in your for condition.

As you were mentioning " In the final iteration of the for loop, i=5 ". In the 5th iteration the i = 4 you are starting from 0th index. So the output is

0> xx == xx
1> xc == xb
2> ca == ba
3> aa == aa
4> az == az 

For the substring function the second parameter in exclusive so substring(4,6) never tries to read the index 6. Thus, the program does not result IndexOutOfBoundsException .

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