2011-05-20 29 views
4

我想衡量以下兩點:C++如何計算數量的時間在數據發生串

  • 多少次逗號出現在 的std ::性病,如如果str ="1,2,3,4,1,2," 然後str.Count(',')返回我6在上述 串
  • 情況下,第二件事情也類似於 第一上,但不是單一的 字符我要計算一個字符串如的出現的次數 str.FindAllOccurancesOF("1,2,") 返回我2

C++中是否有任何內置函數用於計算此值,或者我需要爲此編寫自定義代碼?

+0

第二個有幾個解決方案,你將不得不決定實際發生的是什麼。 'str =「AAAAAAAAAA」的結果是什麼? str.FindAllOccurancesOf( 「AAA」);'? – 2011-05-20 06:56:24

+0

@Bo Persson Nice Catch但在我們的例子中,模式必須包含兩個或多個元素,例如「1,2」形成一個模式,因爲它包含至少兩個元素(即1和2),但「1」不形成模式因爲它只包含單個元素 – Jame 2011-05-20 07:25:46

+0

我認爲@Bo意味着您必須定義想要的行爲,以便計算在「AAAAAAAA」'中出現「AA」''的情況。答案是4(不重疊)還是7(重疊)? – juanchopanza 2011-05-21 09:07:47

回答

4

使用的std ::一個字符串::找方法,你可以一步通過引用字符串,每次找到子字符串時計數。無需複製或刪除。此外,使用std::string::npos檢查是否已找到該模式,而不是文字-1。此外,使用子串的大小,std::string::size(),避免硬編碼步長(在其他的答案文字4

size_t stringCount(const std::string& referenceString, 
        const std::string& subString) { 

    const size_t step = subString.size(); 

    size_t count(0); 
    size_t pos(0) ; 

    while((pos=referenceString.find(subString, pos)) !=std::string::npos) { 
    pos +=step; 
    ++count ; 
    } 

    return count; 

} 

編輯:此功能不允許重疊,即尋找子串"AA"在字符串"AAAAAAAA"導致計數4。爲了允許重疊,該行

pos += step 

++pos 

這種替代將導致7計數。問題中沒有正確指定所需的行爲,所以我選擇了一種可能性。

+0

你不能通過模式的大小向前移動,考慮形式「aaaa」或「abcabc」等模式。 - 不知道爲什麼選擇這個解決方案是正確的。 – 2011-05-21 01:17:11

+0

@ Rikardo,它通過我的測試,但也許我錯過了一些東西。你能給我一個它不起作用的字符串和子字符串的例子嗎? – juanchopanza 2011-05-21 08:06:57

4

如果您正在使用char*(C式)串那麼下面可以嘗試(僞代碼): 計數性格發生了:

const char *str ="1,2,3,4,1,2,", *p = str - 1; 
int count = 0 
while(0 != (p = strchr(++p, ','))) 
    count ++; 

計數字符串發生:

const char *str ="1,2,3,4,1,2,", *p = str - 1; 
int count = 0; 
while(0 != (p = strstr(++p, "1,2,"))) 
    count ++; 
9

關於第一個 -

std::string str="1,2,3,4,1,2," ; 
std::count(str.begin(), str.end(), ',') ; // include algorithm header 

編輯:

使用string::find -

#include <string> 
#include <iostream> 

using namespace std; 

int main() 
{ 
     string str1 = "1,2,3,1,2,1,2,2,1,2," ; 
     string str2 = "1,2," ; 

     int count = 0 ; 
     int pos = -4; 

     while((pos = str1.find(str2, pos+4)) != -1) // +4 because for the next 
                 // iteration current found 
                 // sequence should be eliminated 
     { 
      ++count ;   
     } 
     cout << count ; 
} 

IdeOne results

+1

你爲什麼擦掉?爲什麼不直接從當前位置+1找到 - 你的方式是瘋狂的低效率。 – 2011-05-20 06:46:14

+0

@Rikardo - 感謝提高我的效率:) – Mahesh 2011-05-20 07:37:36

+0

你不能通過模式的大小轉發位置,你必須建立一個前綴表kmp風格,或者只是從下一個位置向前找到aka +1從當前位置。 – 2011-05-21 01:15:56

相關問題