Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices in Working with strings in C++ [closed]

Tags:

c++

string

I am currently making a small C++ tool , and I am kind of shocked on the way of How to deal with strings in C++. This is the first time i need to deal with C++ , I have pretty much experience with Managed languages with strong types like Java , C# but I am getting mad with C++ strings.

Are there any best practices to work with strings in C++ ?

A lot of WIN API functions dealing with different type of "strings"

tchar , char* , LPWSTR , LPCSTR ... etc. and converting each type to other is taking a lot of time for me to implement.

Please suggest your way of dealing with strings when converting one type to another. Maybe there is some library to use ?

like image 579
StringBuilder Avatar asked Oct 14 '25 05:10

StringBuilder


1 Answers

Short answer? Use std::string or std::wstring wherever you can is my advice.

std::string strBuffer = "test";
strBuffer += " ... test";
std::string::size_type nStringSize = strBuffer.size();
const char* pszString = strBuffer.c_str();    // pszString contains 
                                              // pointer to memory held 
                                              // by STL string and can be 
                                              // passed into API calls

You can easily obtain a "c style" string (i.e. a pointer to a null terminate char array char* by .c_str() which you can pass into most WinAPI functions as is.

Most of the other types you mention (tchar, LPWSTR, LPCSTR etc) are typedefs to C style arrays (or pointers to C style arrays, or char types) for supporting unicode over multibyte character sets.

like image 170
Konrad Avatar answered Oct 16 '25 19:10

Konrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!