Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

    std::wstring remove_side_spaces(const std::wstring& str) {
        auto begin = std::find_if_not(str.begin(), str.end(), std::iswspace);
        if (begin == str.end()) {
            return std::wstring();
        } else {
            auto end = std::find_if_not(str.rbegin(), str.rend(), std::iswspace);
            return std::wstring(begin, end.base());
        }
    }


Believe it or not, that doesn't compile because begin and end have different types due to begin/end returning different iterator types than rbegin/rend. It could be a bug in both clang and g++.

This works, but I don't like the &strt and &endp:

    std::wstring trim(std::wstring theStr) {
        auto strt = std::find_if_not(theStr.begin(), theStr.end(), std::iswspace);
    
        if (strt == theStr.end()) return L"";
    
        auto endp = std::find_if_not(theStr.rbegin(), theStr.rend(), std::iswspace);
    
        return std::wstring(&*strt,&*endp+1);
    }
The easiest way is to use Boost's string algorithms library, though:

    std::wstring trimb(std::wstring theStr) {
        boost::trim(theStr);
        return theStr;
    }


I also corrected my example. Thanks!




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: