2012-02-20 2 views
3

Pythonには、strip()と呼ばれる非常に便利な関数があります。 C++の似たようなもの?C++のPythonのstrip()と似た関数ですか?

+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の文字列を削除](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を正しく処理するかなり複雑な バージョンを持っています)。

関連する問題