简体   繁体   English

返回字符串“code”在给定字符串中任何位置出现的次数

[英]Return the number of times that the string "code" appears anywhere in the given string

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 inte.net.大家好,我已经通过 inte.net 的一些帮助解决了这个问题。 But the actual problem that I'm facing is this, (str.length()-3) in the for loop.但我面临的实际问题是 for 循环中的(str.length()-3) I don't understand why the str.length()-3 having this -3 in it.我不明白为什么str.length()-3中有这个-3 please explain it...请解释一下...

Inside the for loop, for any index ( i ), it checks that the chars at i and i+2 and i+3 match your requirements.在 for 循环内,对于任何索引 ( i ),它检查ii+2i+3处的字符是否符合您的要求。 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.如果你的i变成你的字符串(或最后一个字符)的长度,那么代码将抛出异常,因为它会尝试在 position 处查找实际上并不存在的char

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;
}

Assume String is length 10 .假设 String 的长度为10 When I goes from 0 to < 10 ie 0 to 9 , the test str.charAt(i+3)=='e' will cause i + 3 to exceed the length of the string when i >= 7 , and throw an exception.当我从0 to < 10 ie 0 to 9时,测试str.charAt(i+3)=='e'将导致i + 3i >= 7时超过字符串的长度,并抛出异常. By limiting i to 3 less than the length , the loop will terminate before the index goes out of bounds.通过将i限制为3 less than the length ,循环将在索引超出范围之前终止。

Regarding your solution, I would offer the following alternative.关于您的解决方案,我会提供以下替代方案。

  • split("co.e",-1) will split on the word co.e where . split("co.e",-1)将拆分单词co.e where . matches any character.匹配任何字符。 The -1 will ensure trailing empty strings will be preserved (in case the string ends with codecodecode So the number array size would be 1 + the number of delimiters encountered so subtracting one is required. -1将确保保留尾随的空字符串(以防字符串以codecodecode因此数字数组大小将为1 + the number of delimiters encountered因此需要减去一个。
public static int countCode(String str) {
        return (int)str.split("co.e",-1).length-1;
}

Since split takes a regex, either code or co.e can be used.由于split采用正则表达式,因此可以使用codeco.e

Updated更新

Better still would be to use Andy Turner's suggestion and increment do i += 3 when do code++ count.更好的方法是使用Andy Turner 的建议,并在 do i += 3 do code++ count 时增加 do i += 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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