如何:在各种字符串类型之间进行转换 VS2010

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

如何:在各种字符串类型之间进行转换

Visual Studio 2010 其他版本Visual Studio 2008 Visual Studio 2005

本主题演示如何将各种Visual C++ 字符串类型转换为其他字符串。可以转换的字符串类型包括char *、wchar_t*、_bstr_t、CComBSTR、CString、basic_string 和System.String。在所有情况下,在将字符串转换为新类型时,都会创建字符串的副本。对新字符串进行的任何更改都不会影响原始字符串,反之亦然。

示例

--------------------------------------------------------------------------------

说明

此示例演示如何从char * 转换为上面列出的其他字符串类型。char * 字符串(也称为C 样式字符串)使用null 字符指示字符串的末尾。 C 样式字符串通常每个字符需要一个字节,但也可以使用两个字节。在下面的示例中,char * 字符串有时称为多字节字符字符串,因为该字符串数据是从Unicode 字符串转换得到的。可对char * 字符串执行单字节和多字节字符(MBCS) 函数运算。

代码

复制// convert_from_char.cpp

// compile with: /clr /link comsuppw.lib

#include

#include

#include

#include "atlbase.h"

#include "atlstr.h"

#include "comutil.h"

using namespace std;

using namespace System;

int main()

{

// Create and display a C style string, and then use it

// to create different kinds of strings.

char *orig = "Hello, World!";

cout << orig << " (char *)" << endl;

// newsize describes the length of the

// wchar_t string called wcstring in terms of the number

// of wide characters, not the number of bytes.

size_t newsize = strlen(orig) + 1;

// The following creates a buffer large enough to contain

// the exact number of characters in the original string

// in the new format. If you want to add more characters

// to the end of the string, increase the value of newsize

// to increase the size of the buffer.

wchar_t * wcstring = new wchar_t[newsize];

// Convert char* string to a wchar_t* string.

size_t convertedChars = 0;

mbstowcs_s(&convertedChars, wcstring, newsize, orig, _TRUNCATE); // Display the result and indicate the type of string that it is.

wcout << wcstring << _T(" (wchar_t *)") << endl;

// Convert the C style string to a _bstr_t string.

_bstr_t bstrt(orig);

// Append the type of string to the new string

// and then display the result.

bstrt += " (_bstr_t)";

cout << bstrt << endl;

// Convert the C style string to a CComBSTR string.

CComBSTR ccombstr(orig);

if (ccombstr.Append(_T(" (CComBSTR)")) == S_OK)

{

CW2A printstr(ccombstr);

cout << printstr << endl;

}

// Convert the C style string to a CstringA and display it.

CStringA cstringa(orig);

cstringa += " (CStringA)";

cout << cstringa << endl;

// Convert the C style string to a CStringW and display it.

CStringW cstring(orig);

cstring += " (CStringW)";

// To display a CStringW correctly, use wcout and cast cstring

// to (LPCTSTR).

wcout << (LPCTSTR)cstring << endl;

// Convert the C style string to a basic_string and display it.

string basicstring(orig);

basicstring += " (basic_string)";

cout << basicstring << endl;

相关文档
最新文档