开发者

How can I substring a TCHAR

开发者 https://www.devze.com 2023-01-22 12:58 出处:网络
I have a TCHAR and value as below: TCHARszDestPathRoot[MAX_PATH]=\"String This\"; No开发者_如何转开发w I want the 1st three character fromTCHAR , like below:

I have a TCHAR and value as below:

TCHAR          szDestPathRoot[MAX_PATH]="String This";

No开发者_如何转开发w I want the 1st three character from TCHAR , like below:

szDestPathRoot.substring(0,2);

How can I do this.


TCHAR[] is a simple null-terminated array (rather than a C++ class). As a result, there's no ".substring()" method.

TCHAR[] (by definition) can either be a wide character string (Unicode) or a simple char string (ASCII). This means there are wcs and str equivalents for each string function (wcslen() vs strlen(), etc etc). And an agnostic, compile-time TCHAR equivalent that can be either/or.

The TCHAR equivalent of strncpy() is tcsncpy().

Final caveat: to declare a TCHARliteral, it's best to use the _T() macro, as shown in the following snippet:

TCHAR szDestPathRoot[MAX_PATH] = _T("String This");
TCHAR szStrNew[4];
_tcsncpy (str_new, szTestPathRoot, 3);

You may find these links to be of interest:

  • http://msdn.microsoft.com/en-us/library/xdsywd25%28VS.71%29.aspx
  • http://www.i18nguy.com/unicode/c-unicode.html
  • http://msdn.microsoft.com/en-us/library/5dae5d43(VS.80).aspx (for using the secure _tcsncpy_s)


TCHAR szDestPathRoot[MAX_PATH]="String This";
TCHAR substringValue[4] = {0};
memcpy(substringValue, szDestPathRoot, sizeof(TCHAR) * 3);


As you have tagged your question with "C++" you can use the string classes of the std library:

std::wstring strDestPathRoot( _T("String This") );
strDestPathRoot.substr( 0, 2 );


This is somewhat ugly but if you know for sure that:

  1. The string holds at least 4 TCHAR (3 chars plus the terminating NUL)
  2. The content of the string can be modified (which is the case in your example).
  3. You don't have to keep the original string intact

You could just put a terminating NUL at the 4th position to make the string 3 char long.

szDestPathRoot[3] = _T('\0');

Note that this operation is destructive to the original string

You should really be using a string class in C++ code though.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号