【问题标题】:Return the number of times that the string "code" appears anywhere in the given string返回字符串 \"code\" 在给定字符串的任何位置出现的次数
【发布时间】:2023-01-02 15:46:44
【问题描述】:
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;
}

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

【问题讨论】:

  • 因为str.charAt(i+3)。如果您不使用 3`,您将获得 StringIndexOutOfBoundException
  • 嗨...但是,我问的是 for 循环条件 str.length()-3。为什么会这样,-3 的目的是什么。 -3 是如何在我的代码中生效的……请解释一下……

标签: java string underscore-java


【解决方案1】:

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

【讨论】:

  • 嗨...但是,我问的是 for 循环条件 str.length()-3。为什么会这样,-3 的目的是什么。 -3 是如何在我的代码中生效的……请解释一下……
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 2020-08-18
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    相关资源
    最近更新 更多