Home > Software engineering >  Why am I doing i < a.length()-1 in my for loop
Why am I doing i < a.length()-1 in my for loop

Time:10-14

The question is given two strings, return the number of the positions where they contain the same length 2 substring.

The code I wrote works but my question is why do I have to add the minus 1 to line 3 which is this part: i<a.length()-1

(I know it has something to do with me using (i,i 2))

public int stringMatch(String a, String b) {
  
  int count = 0;
  if (a.length() < b.length()) {
  for (int i=0; i<a.length()-1; i  ) {
    if (a.substring(i,i 2).equals(b.substring(i,i 2))) {
      count  ;
      }
    }
  } else {
    for (int i=0; i<b.length()-1; i  ) {
    if (b.substring(i,i 2).equals(a.substring(i,i 2))) {
      count  ;
   }
   }
  }
return count;
}

CodePudding user response:

String.length() function returns length of the string, but when you access the characters you access it using index. That is why you have to do "-1".

For Example:

String s = "Hello";

Length is 5. Index is from 0 to 4.

CodePudding user response:

Since the substring goes from the index i (included) to i 2 (excluded), in order not to go out of the substring the loop needs to finish 1 step before.

  • Related