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

大家好,我已经通过 inte.net 的一些帮助解决了这个问题。 但我面临的实际问题是 for 循环中的(str.length()-3) 我不明白为什么str.length()-3中有这个-3 请解释一下...

在 for 循环内,对于任何索引 ( i ),它检查ii+2i+3处的字符是否符合您的要求。 如果你的i变成你的字符串(或最后一个字符)的长度,那么代码将抛出异常,因为它会尝试在 position 处查找实际上并不存在的char

为了发布某人可能在生产系统中实际使用的答案,我们可以尝试一种替代方法:

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

假设 String 的长度为10 当我从0 to < 10 ie 0 to 9时,测试str.charAt(i+3)=='e'将导致i + 3i >= 7时超过字符串的长度,并抛出异常. 通过将i限制为3 less than the length ,循环将在索引超出范围之前终止。

关于您的解决方案,我会提供以下替代方案。

  • split("co.e",-1)将拆分单词co.e where . 匹配任何字符。 -1将确保保留尾随的空字符串(以防字符串以codecodecode因此数字数组大小将为1 + the number of delimiters encountered因此需要减去一个。
public static int countCode(String str) {
        return (int)str.split("co.e",-1).length-1;
}

由于split采用正则表达式,因此可以使用codeco.e

更新

更好的方法是使用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