2012-02-20 3 views
3

В Python есть очень полезная функция: strip(). Любые подобные в C++?Аналогичная функция в C++ для полосы Python()?

+0

http://stackoverflow.com/questions/352055/best-algorithm-to-strip-leading-and-trailing-spaces-in -c – Veger

+0

Возможный дубликат [Что лучший способ обрезать std :: string] (http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring) –

+0

Возможный дубликат [ Python strip string] (http://stackoverflow.com/questions/1038824/python-strip-a-string) – Marcin

ответ

5

Нет ничего встроенного; Я использовал что-то вроде:

template <std::ctype_base::mask mask> 
class IsNot 
{ 
    std::locale myLocale;  // To ensure lifetime of facet... 
    std::ctype<char> const* myCType; 
public: 
    IsNot(std::locale const& l = std::locale()) 
     : myLocale(l) 
     , myCType(&std::use_facet<std::ctype<char> >(l)) 
    { 
    } 
    bool operator()(char ch) const 
    { 
     return ! myCType->is(mask, ch); 
    } 
}; 

typedef IsNot<std::ctype_base::space> IsNotSpace; 

std::string 
trim(std::string const& original) 
{ 
    std::string::const_iterator right = std::find_if(original.rbegin(), original.rend(), IsNotSpace()).base(); 
    std::string::const_iterator left = std::find_if(original.begin(), right, IsNotSpace()); 
    return std::string(left, right); 
} 

который работает очень хорошо. (Теперь у меня есть значительно более сложная версия , которая правильно обрабатывает UTF-8.)

Смежные вопросы