Home > Software design >  Return the number of times that the string "code" appears anywhere in the given string
Return the number of times that the string "code" appears anywhere in the given string

Time:01-02

public int countCode(String str) {
  int code = 0;
  
  for(int i=0; i<str.length()-3; i  ){
    if(str.substring(i, i 2).equals("co") && str.charAt(i 3)=='e'){
      code  ;
    }
  }
  return code;
}

Hi guys, I've solved this problem by some help among the internet. But the actual problem that I'm facing is this, (str.length()-3) in the for loop. I don't understand why the str.length()-3 having this -3 in it. please explain it...

CodePudding user response:

Inside the for loop, for any index (i), it checks that the chars at i and i 2 and i 3 match your requirements. If your i becomes length of your string (or last character), then the code will throw exception since it will try to find char at position which is not really there.

CodePudding user response:

In the interest of posting an answer which someone might actually use in a production system, we can try a replacement approach:

public int countCode(String str) {
    return (str.length() - str.replace("code", "").length()) / 4;
}
  • Related