How to trim an std::string?

EDIT Since c++17, some parts of the standard library were removed. Fortunately, starting with c++11, we have lambdas which are a superior solution. #include <algorithm> #include <cctype> #include <locale> // trim from start (in place) static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); })); } // trim from … Read more

Is std::string size() a O(1) operation?

If you’re asking if MSVC’s implementation of string::size() has constant complexity, then the answer is yes. But Don Wakefield mentioned Table 65 in 23.1 of the C++ Standard where it says that the complexity of size() should follow what’s said in ‘Note A’. Note A says: Those entries marked ‘‘(Note A)’’ should have constant complexity. … Read more

I want to convert std::string into a const wchar_t *

First convert it to std::wstring: std::wstring widestr = std::wstring(str.begin(), str.end()); Then get the C string: const wchar_t* widecstr = widestr.c_str(); This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.

How do you convert CString and std::string std::wstring to each other?

According to CodeGuru: CString to std::string: CString cs(“Hello”); std::string s((LPCTSTR)cs); BUT: std::string cannot always construct from a LPCTSTR. i.e. the code will fail for UNICODE builds. As std::string can construct only from LPSTR / LPCSTR, a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA as an intermediary. CString cs … Read more

Can a std::string contain embedded nulls?

Yes you can have embedded nulls in your std::string. Example: std::string s; s.push_back(‘\0’); s.push_back(‘a’); assert(s.length() == 2); Note: std::string‘s c_str() member will always append a null character to the returned char buffer; However, std::string‘s data() member may or may not append a null character to the returned char buffer. Be careful of operator+= One thing … Read more

How to get the number of characters in a std::string?

If you’re using a std::string, call length(): std::string str = “hello”; std::cout << str << “:” << str.length(); // Outputs “hello:5” If you’re using a c-string, call strlen(). const char *str = “hello”; std::cout << str << “:” << strlen(str); // Outputs “hello:5” Or, if you happen to like using Pascal-style strings (or f***** strings … Read more