windows 如何对 TCHAR 进行子串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4039850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I substring a TCHAR
提问by Simsons
I have a TCHAR and value as below:
我有一个 TCHAR 和值如下:
TCHAR szDestPathRoot[MAX_PATH]="String This";
Now I want the 1st three character from TCHAR , like below:
现在我想要 TCHAR 的第一个三个字符,如下所示:
szDestPathRoot.substring(0,2);
How can I do this.
我怎样才能做到这一点。
回答by paulsm4
TCHAR[]
is a simple null-terminated array (rather than a C++ class). As a result, there's no ".substring()" method.
TCHAR[]
是一个简单的以空字符结尾的数组(而不是 C++ 类)。因此,没有“.substring()”方法。
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.
TCHAR[]
(根据定义)可以是宽字符串 (Unicode) 或简单字符字符串 (ASCII)。此装置有wcs
和str
等同物对于每个字符串功能(wcslen()
VS strlen()
,等等等等)。和一个不可知的,编译时TCHAR
等价物,可以是/或。
The TCHAR
equivalent of strncpy()
is tcsncpy()
.
该TCHAR
等效strncpy()
IS tcsncpy()
。
Final caveat: to declare a TCHAR
literal, it's best to use the _T()
macro, as shown in the following snippet:
最后的警告:要声明TCHAR
文字,最好使用_T()
宏,如以下代码段所示:
TCHAR szDestPathRoot[MAX_PATH] = _T("String This");
TCHAR szStrNew[4];
_tcsncpy (str_new, szTestPathRoot, 3);
You may find these links to be of interest:
您可能会发现这些链接很有趣:
回答by tidwall
TCHAR szDestPathRoot[MAX_PATH]="String This";
TCHAR substringValue[4] = {0};
memcpy(substringValue, szDestPathRoot, sizeof(TCHAR) * 3);
回答by Alex Jasmin
This is somewhat ugly but if you know for sure that:
这有点难看,但如果你确定:
- The string holds at least 4 TCHAR (3 chars plus the terminating NUL)
- The content of the string can be modified (which is the case in your example).
- You don't have to keep the original string intact
- 该字符串至少包含 4 个 TCHAR(3 个字符加上终止的 NUL)
- 可以修改字符串的内容(在您的示例中就是这种情况)。
- 您不必保持原始字符串完好无损
You could just put a terminating NUL at the 4th position to make the string 3 char long.
您可以在第 4 个位置放置一个终止 NUL 以使字符串长度为 3 个字符。
szDestPathRoot[3] = _T('std::wstring strDestPathRoot( _T("String This") );
strDestPathRoot.substr( 0, 2 );
');
Note that this operation is destructive to the original string
注意这个操作对原始字符串是破坏性的
You should really be using a string class in C++ code though.
不过,您确实应该在 C++ 代码中使用字符串类。
回答by Flinsch
As you have tagged your question with "C++" you can use the string classes of the std library:
当您用“C++”标记您的问题时,您可以使用 std 库的字符串类:
##代码##