2014-09-02 104 views
1

我正在尋找一個功能,如果提供給例如匹配整個單詞:匹配整個字符串大小寫不敏感

std::string str1 = "I'm using firefox browser"; 
std::string str2 = "The quick brown fox."; 
std::string str3 = "The quick brown fox jumps over the lazy dog."; 

只有str2str3應該匹配字fox。所以,在單詞之前或之後是否有像句號(。)或逗號(,)這樣的符號並且它應該匹配並且無關緊要,並且它也必須同時進行不區分大小寫的搜索。

我發現了很多方法來搜索不區分大小寫的字符串,但我想知道匹配整個單詞的東西。

+0

http://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c – 2014-09-02 11:55:13

+0

你能給的調用示例該功能,以及預期的結果? – juanchopanza 2014-09-02 11:56:04

+0

結果可以是'bool'來表示匹配的字符串是否被找到,或者是一個索引位置,就像'std :: find'和'std :: search'函數一樣。 – cpx 2014-09-02 12:06:29

回答

0

我想推薦C++ 11的std::regex。但是,它還沒有與g ++ 4.8一起工作。所以我建議更換boost::regex

#include<iostream> 
#include<string> 
#include<algorithm> 
#include<boost/regex.hpp> 

int main() 
{ 
    std::vector <std::string> strs = {"I'm using firefox browser", 
             "The quick brown fox.", 
             "The quick brown Fox jumps over the lazy dog."}; 
    for(auto s : strs) { 
     std::cout << "\n s: " << s << '\n'; 
     if(boost::regex_search(s, boost::regex("\\<fox\\>", boost::regex::icase))) { 
      std::cout << "\n Match: " << s << '\n'; 
     } 
    } 
    return 0; 
} 

/* 
    Local Variables: 
    compile-command: "g++ --std=c++11 test.cc -lboost_regex -o ./test.exe && ./test.exe" 
    End: 
*/ 

輸出是:

s: I'm using firefox browser 

s: The quick brown fox. 

Match: the quick brown fox. 

s: The quick brown Fox jumps over the lazy dog. 

Match: the quick brown fox jumps over the lazy dog. 
+0

你可以使用'boost :: regex :: icase'來區分大小寫而不是':: tolower'。 – rjnilsson 2014-09-02 12:52:51

+0

@Cwan感謝您的建議。完成。 – Tobias 2014-09-02 12:56:33

相關問題