簡體   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