Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a substring of a LPCTSTR?

Tags:

c++

string

winapi

How do I get a substring of a LPCTSTR?

like image 228
Holtorf Avatar asked Nov 30 '22 06:11

Holtorf


2 Answers

LPCSTR is just fancy name for char *, it doesn't have methods.

If you use std::string you could use the find and substr methods to extract the first and second part of the string.

Edit: As noted by Christoph, the type of TCHAR differs depending on if UNICODE is defined or not. If UNICODE is defined (check with #ifdef UNICODE, do a Google search on preprocessor to learn more about things like #define and #ifdef) you need to use std::wstring instead of std::string.

Edit 2: An easier solution than checking if you need to use std::string or std::wstring all the time, is to follow the advice of Konrad Rudolph and create a new typedef similar to std::string and std::wstring. Something like this:

typedef std::basic_string<TCHAR> tstring;

And then use that string type internally.

like image 120
Some programmer dude Avatar answered Dec 02 '22 19:12

Some programmer dude


As an alternative, as LPCTSTR is a TCHAR*, then you can "substring" quite easily using _tcschr...depending on what your use case is.

TCHAR* exepath = getTheFullPathToThisProcess();
TCHAR* extension = _tcschr(exepath,'.'); //extension is a valid c-string containing '.exe'
//where is the last "\"?
TCHAR* slash = _tcsrchr(exepath,'\\');
*slash = 0;//exepath is now shortened to the path pre the filename of this process.

Might be easier for you if you are comfortable in c-string land.

EDIT : Forgot that LPCTSTR is a const! You would need to do a _stprintf(copy,"%s",exepath) in that case... so may not be worth it. But will leave this here as an alternative anyway.

like image 28
Dennis Avatar answered Dec 02 '22 18:12

Dennis