2011-02-09 86 views

回答

10

你可以大寫兩個字符串並使用常規查找。 (注意:如果你有Unicode字符串,這種方法可能不正確。)

在Boost中,對於不區分大小寫的搜索還有ifind_first。 (請注意,它返回一個範圍而不是size_t)。

#include <string> 
#include <boost/algorithm/string/find.hpp> 
#include <cstdio> 
#include <cctype> 

std::string upperCase(std::string input) { 
    for (std::string::iterator it = input.begin(); it != input.end(); ++ it) 
    *it = toupper(*it); 
    return input; 
} 

int main() { 
    std::string foo = "1 FoO 2 foo"; 
    std::string target = "foo"; 

    printf("string.find: %zu\n", foo.find(target)); 

    printf("string.find w/ upperCase: %zu\n", upperCase(foo).find(upperCase(target))); 

    printf("ifind_first: %zu\n", boost::algorithm::ifind_first(foo, target).begin() - foo.begin()); 

    return 0; 
} 
+1

+1 Boost.String算法是項目的先決條件:) –

+0

我剛剛給了ifind_first一個測試驅動器,它比將2個字符串轉換爲lower casee(使用boost)並使用std :: string :: find要慢。 – goji

+0

但在一般情況下它不適用於Unicode。 「ß」和「SS」應該相等,但Boost字符串算法不能處理這個問題。 – dalle

0
for(int i=0; i<yourString.length() 
    && tolower(yourString[i])!=yourLoweredChar; i++) 
{ 
    return i; 
} 
return -1; 

如果返回-1,那麼你的目標字符是不是有

否則給人的焦炭

2

做任何事情之前看中的第一occurrance,看看

http://www.gotw.ca/gotw/029.htm

並看看是否使用自定義字符traits類不是你想要的。

2

這是我會建議,(同@programmersbook)

#include <iostream> 
#include <algorithm> 
#include <string> 

bool lower_test (char l, char r) { 
    return (std::tolower(l) == std::tolower(r)); 
} 

int main() 
{ 
    std::string text("foo BaR"); 
    std::string search("bar"); 

    std::string::iterator fpos = std::search(text.begin(), text.end(), search.begin(), search.end(), lower_test); 
    if (fpos != text.end()) 
    std::cout << "found at: " << std::distance(text.begin(), fpos) << std::endl; 
    return 0; 
} 
相關問題