読者です 読者をやめる 読者になる 読者になる

extension std::basic_string

std::string に trim_left と trim_right
std::wstring に wtrim_left と wtrim_right を拡張する



#ifndef SHAND_EXTENSION_STD_STRING_INCLUDE
#define SHAND_EXTENSION_STD_STRING_INCLUDE

#include <string>
#include <functional> // std::tr1::result_of

namespace shand { namespace extension {

// trim_left
struct trim_left {
    typedef std::string result_type;

    std::string operator()(const std::string& source) const
    {
        std::string temp = source;
        temp.erase(0, temp.find_first_not_of(' '));
        return temp;
    }
};

struct wtrim_left {
    typedef std::wstring result_type;

    std::wstring operator()(const std::wstring& source) const
    {
        std::wstring temp = source;
        temp.erase(0, temp.find_first_not_of(L' '));
        return temp;
    }
};

// trim_right
struct trim_right {
    typedef std::string result_type;

    std::string operator()(const std::string& source) const
    {
        std::string temp = source;
        temp.erase(temp.find_last_not_of(' ')+1);
        return temp;
    }
};

struct wtrim_right {
    typedef std::wstring result_type;

    std::wstring operator()(const std::wstring& source) const
    {
        std::wstring temp = source;
        temp.erase(temp.find_last_not_of(L' ')+1);
        return temp;
    }
};

template <class CharT, class Alloc, class Func>
inline typename std::tr1::result_of<Func(const std::basic_string<CharT, Alloc>&)>::type
    operator|(const std::basic_string<CharT, Alloc>& source, Func func)
{
    return func(source);
}

}} // namespace shand::extension

#endif // SHAND_EXTENSION_STD_STRING_INCLUDE


サンプル

#include <iostream>
#include <string>
#include <shand/extension/string.hpp>

using namespace std;
using namespace shand::extension;

int main()
{
    string str = " abc ";
    string result = str|trim_left()|trim_right();

    cout << "|" << result << "|" << endl; // |abc|

    return 0;
}


ライブラリまとめ