3 ms·
This guy's biggest problem is that he doesn't know the standard library very well. I admit it's ugly, but the code below removes whitespace using only standard
by jlarocco 14y ago
This guy's biggest problem is that he doesn't know the standard library very well.
I admit it's ugly, but the code below removes whitespace using only standard C++ calls. There's also an isspace() function from the <locale> header that takes a specific locale, but I'm not sure it's important for whitespace.
std::wstring removeSpaces(std::wstring theStr) {
return std::wstring(theStr.begin(),
std::remove_if(theStr.begin(),
theStr.end(),
std::iswspace));
}
There's also codec conversion in the <locale> header [1]. It's also pretty ugly, but it's easier to understand than his home grown solution, and if nothing else, is already debugged. And to be honest, if you're using C++ you should be used to the code being verbose and ugly.
[1] http://en.cppreference.com/w/cpp/locale/codecvt http://en.cppreference.com/w/cpp/locale/codecvt
- to3m 14y agoThe code in the blog post removes only leading or trailing white space, not all of it.
- pdhborges 14y agostd::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()); } }
- jlarocco 14y agoBelieve 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; }
- pdhborges 14y agoI also corrected my example. Thanks!