2012-07-06 429 views
0

我有一個太長的字符串,我想查找並找到所有需要的單詞。例如,我想查找字符串中所有「蘋果」的位置。你能告訴我我是怎麼做到的嗎? 謝謝在字符串中查找所有想要的單詞

+1

查找到的boost ::正則表達式,如果你需要匹配更復雜的東西。否則,堅持Frerich Raabe的回答。 – 2012-07-06 13:02:36

回答

4

重複應用std::string::find如果您使用的是C++字符串,或者std::strstr如果您使用的是C字符串;在這兩種情況下,在每次迭代中,在最後一次匹配後開始搜索n個字符,其中n是單詞的長度。

std::string str="one apple two apples three apples"; 
std::string search="apple"; 
for(std::string::size_type pos=0; pos<str.size(); pos+=search.size()) 
{ 
    pos=str.find(search, pos); 
    if(pos==std::string::npos) 
     break; 
    std::cout<<"Match found at: "<<pos<<std::endl; 
} 

link

+0

這不會找到重疊的匹配 - 例如對於模式眼睛和眼睛線眼睛而言,迄今爲止給出的所有答案只能找到第一個出現。 – 2012-07-06 13:12:49

+0

我認爲如果匹配在字符串的末尾,就會中斷。如果'str'會以'apple'結尾。在這種情況下,你可以調用'std :: string :: find(search,pos);',其值'pos'等於'size()'。不確定這是否允許。 – 2012-07-06 13:18:32

+0

@IvanVergiliev:如果這是你想要的,取決於你想用這個函數實現什麼規範(這兩個規範都有有效的用例);仍然,所有需要的是將'pos + = ...'改爲'pos ++'。 – 2012-07-06 18:55:27

2

使用一個循環反覆調用std::string::find;在每次迭代,你開始尋找超越你最後的命中:

std::vector<std::string::size_type> indicesOf(const std::string &s, 
               const std::string &needle) 
{ 
    std::vector<std::string::size_type> indices; 
    std::string::size_type p = 0; 
    while (p < s.size()) { 
    std::string::size_type q = s.find(needle, p); 
    if (q == std::string::npos) { 
     break; 
    } 
    indices.push_back(q); 
    p = q + needle.size(); // change needle.size() to 1 for overlapping matches 
    } 
    return indices; 
} 
0
void findApples(const char* someString) 
{ 
    const char* loc = NULL; 
    while ((loc = strstr(someString, "apple")) != NULL) { 
     // do something 
     someString = loc + strlen("apple"); 
    } 
} 
+0

鑑於qustion是關於C++的,我會考慮一個關於'std :: string'的回答更合適。 – 2012-07-06 13:01:01

相關問題