2014-02-19 18 views
0

我收到了一個代碼。它假設每次發現「code」,「cope」,「coze」,「cole」或「core」時,都會給出一個計數值的輸出。例如:countCode(「aaacodebbb」)它應該是1,但發現爲0.substr的錯誤輸出

int countCode(const string& inStr) { 
    int count = 0; 
    for (unsigned i = 0; i < inStr.length(); i++) { 
     if (inStr.substr(i,i+3) == "code" || inStr.substr(i,i+3) == "coze" || inStr.substr(i,i+3) == "cope" || inStr.substr(i,i+3) == "core" || inStr.substr(i,i+3) == "cole") { 
      count++; 
     } 
    } 
    return count; 
} 
+0

你試過打印(或在調試器中檢查)'inStr.substr(i,i + 3)'嗎? – John3136

回答

2
string substr (size_t pos = 0, size_t len = npos) const; 

這第二個參數的意思是長度,不是最後一個字符位置。您需要改用inStr.substr(i,4)

此外,您知道當有剩餘的字符串中小於4個字符不能出現四個字符的字符串,這樣你就可以像使其更符合邏輯(以及可能的泥潭有效):

int countCode (const string& inStr) { 
    int count = 0; 
    size_t len = inStr.length(); 
    if (len >= 4) { 
     for (size_t i = 0; i <= len - 4; i++) { 
      if (inStr.substr(i,4) == "code" || ...) { 
       count++; 
      } 
     } 
    } 
} 

另請注意,使用size_t這是更自然的類型來處理字符串中的大小和位置。

2

如果您檢查this substr reference你會看到第二個參數是子串的長度,而不是結束位置。

2

substr()的第二個參數是計數,而不是結束位置。

basic_string substr(size_type pos = 0, 
       size_type count = npos) const; 

參數

pos  - position of the first character to include 
    count - length of the substring 
    ^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^ 

這意味着,你應該使用

inStr.substr(i,4)