如何将 System::WideString 转换为 char* 或反之亦然?

发布于 2024-08-15 11:13:58 字数 106 浏览 10 评论 0 原文

我遇到一种情况,需要将 char*WideString 进行比较。
如何在 C++ 中将 WideString 转换为 char*?

I have a situation where I need to compare a char* with a WideString.
How do I convert the WideString to a char* in C++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

酒浓于脸红 2024-08-22 11:13:58

比较 System::WideString 对象带有 char* (正如问题 body 所说的那样),您可以创建一个新的 WideString 对象从指针,然后使用普通的 == 运算符。该类有多个构造函数,其中包括一个用于 const char* 的构造函数。

char* foo = ...;
WideString bar = ...;
if (WideString(foo) == bar)
  std::cout << "They're equal!\n";

事实上,只要 WideString 对象位于左侧,您甚至不需要调用构造函数,因为指针会自动转换。

if (bar == foo) { ... }

要将 WideString 转换char* (正如问题 title 所说的那样),您可以考虑使用 AnsiString 类型。它们之间可以相互转换。要获取普通指针,请调用 c_str 方法,就像使用 std::string 一样。

WideString bar = ...;
AnsiString foo = bar;
std::cout << foo.c_str();

To compare a System::WideString object with a char* (as the question body says you want to do), you can create a new WideString object from the pointer and then use ordinary == operator. The class has several constructors, including one for const char*.

char* foo = ...;
WideString bar = ...;
if (WideString(foo) == bar)
  std::cout << "They're equal!\n";

In fact, as long as the WideString object is on the left, you don't even need the constructor call because the pointer will be converted automatically.

if (bar == foo) { ... }

To convert a WideString to a char* (as the question title says you want to do), you might consider using the AnsiString type. They're convertible between each other. To get the ordinary pointer, call the c_str method, just like you would with std::string.

WideString bar = ...;
AnsiString foo = bar;
std::cout << foo.c_str();
人生戏 2024-08-22 11:13:58

不可能。实际上,您混合了两个不同的概念:

  • Widestring 意味着 UTF-16 编码中的缓冲区。
  • char* 可以包含从 UTF-8 到纯 ASCII 文本的任何内容(在这种情况下,仅当您的宽字符串不包含非 ASCII 字符时才可转换)。

请参阅我对 https://stackoverflow.com/questions/1049947/should-utf 的回答-16-be-considered-harmful 关于如何正确处理文本。

Not possible. Actually, you mixed two different concepts:

  • Widestring implies a buffer in UTF-16 encoding.
  • char* may contain anything, from UTF-8 to ASCII-only text (in which case, this is convertable only if your widestring does not contain non-ASCII characters).

Please see my answer to https://stackoverflow.com/questions/1049947/should-utf-16-be-considered-harmful about how to properly handle text.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文