对C++ string的一些补充

std::wstring string2wstring(std::string str)
{   
    std::wstring result;
    int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
    wchar_t* buffer = new wchar_t[len + 1];
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);   
    buffer[len] = L'\0';
    result.append(buffer);
    delete[] buffer;

    return result;   
}

std::string wstring2string(std::wstring wstr)
{   
    std::string result;
    int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);   
    char* buffer = new char[len + 1];   
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);   
    buffer[len] = '\0';
    result.append(buffer);
    delete[] buffer;
    
    return result;   
} 

std::vector<std::wstring> Split(const std::wstring & str, wchar_t delimeter)
{
    size_t last = 0;
    size_t index = str.find_first_of(delimeter, last);
    std::vector<std::wstring> items;
    while (index != std::wstring::npos)
    {
        items.push_back(str.substr(last, index-last));
        last = index + 1;
        index = str.find_first_of(delimeter, last);
    }

    items.push_back(str.substr(last));

    return items;
}

inline std::string& lTrim(std::string &ss)
{   
    std::string::iterator p = std::find_if(ss.begin(), ss.end(), std::not1(std::ptr_fun(isspace)));
    ss.erase(ss.begin(), p);
    return ss;
}   

inline std::string& rTrim(std::string &ss)
{
    std::string::reverse_iterator p = std::find_if(ss.rbegin(), ss.rend(), std::not1(std::ptr_fun(isspace)));   
    ss.erase(p.base(), ss.end());
    return ss;
}   

inline std::string& trim(std::string &st)   
{   
    lTrim(rTrim(st));
    return st;
}   

 

posted @ 2012-06-20 17:01  友学友  阅读(500)  评论(0编辑  收藏  举报