2011-02-09 10 views

Odpowiedz

10

Można pisać dużymi literami i używać zwykłego znaleziska. (Uwaga: to podejście może nie być poprawne, jeśli masz ciąg znaków Unicode.)

W funkcji Boost jest również ifind_first w przypadku wyszukiwania bez rozróżniania wielkości liter. (zwróć uwagę, że zwraca zakres zamiast 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 Algorithms jest warunkiem wstępnym dla projektów :) –

+0

Po prostu dałem ifind_first napęd testowy i było wolniejsze niż konwersja 2 łańcuchów na mniejsze litery (za pomocą boost) i użycie std :: string :: find. – goji

+0

Ale nie będzie działać dla Unicode w ogólnym przypadku. "ß" i "SS" powinny porównywać równe, ale algorytmy algorytmów wzmocnienia nie radzą sobie z tym. – dalle

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

Jeśli zwracane jest -1 wtedy twój cel char nie ma

inny daje pierwszy occurrance z char

2

zanim cokolwiek ozdobnego, rzucić okiem na

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

i sprawdź, czy użycie niestandardowej klasy cech postaci nie jest tym, czego potrzebujesz.

2

to, co bym sugerował, (tak samo jak @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; 
} 
Powiązane problemy