问题描述
我正在尝试在Windows 应用商店"(又名 Metro 风格)应用程序中用 C++/CX 编写几行代码,我很惊讶地看到 Platform::String 缺少许多基本的字符串操作,例如 "替换" 或 索引".
I am trying to write a few lines of code in C++/CX in a "Windows Store" (aka Metro Style) application, and I am surprised to see that Platform::String is missing many basic string operations like "replace" or "index of".
我想我可以使用内部数据,将其传递给 std:string 实例并应用我需要的操作,但我想知道我是否缺少执行这些操作的某些仅平台 :: *"方式.
I suppose I could use the internal data, pass it to a std:string instance and apply the operations I need, but I would like to know if I am missing some "Platform::* only" way of doing these operations.
请注意这个问题是关于 C++/CX,而不是 C#.
推荐答案
Windows 运行时字符串类型,HSTRING
是不可变的并且是引用计数的.
The Windows Runtime string type, HSTRING
is immutable and is reference counted.
C++/CX 中的 Platform::String
类型只是对 HSTRING
类型及其支持的少数操作的包装(参见以Windows 运行时 C++ 函数 列表中的 Windows
).
The Platform::String
type in C++/CX is simply a wrapper around the HSTRING
type and the handful of operations that it supports (see the functions that start with Windows
in the Windows Runtime C++ Functions list).
没有改变字符串的操作,因为字符串类型是不可变的(因此没有Replace
).有一些非变异操作(肯定比 C++ 的 std::wstring
少).
There are no operations that mutate the string because the string type is immutable (hence why there is no Replace
). There are a few non-mutating operations (certainly fewer than C++'s std::wstring
).
Platform::String
确实提供了 Begin()
和 End()
成员函数(和非成员 begin()
和 end()
重载)将随机访问迭代器返回到字符串中(它们返回指针,wchar_t const*
,并且指针是有效的随机访问迭代器).您可以将这些迭代器与任何采用随机访问迭代器且不尝试改变底层序列的 C++ 标准库算法一起使用.例如,考虑使用 std::find
来查找字符第一次出现的索引.
Platform::String
does provide Begin()
and End()
member functions (and non-member begin()
and end()
overloads) that return random access iterators into the string (they return pointers, wchar_t const*
, and pointers are valid random access iterators). You can use these iterators with any of the C++ Standard Library algorithms that take random access iterators and do not attempt to mutate the underlying sequence. For example, consider using std::find
to find the index of the first occurrence of a character.
如果您需要改变字符串,请使用 std::wstring
或 std::vector
.理想情况下,请考虑在您的程序中尽可能多地使用 C++ std::wstring
,并且仅在需要与其他 Windows 互操作的地方使用 C++/CX Platform::String
运行时组件(即跨越 ABI 边界).
If you need to mutate a string, use std::wstring
or std::vector<wchar_t>
. Ideally, consider using the C++ std::wstring
as much as possible in your program and only use the C++/CX Platform::String
where you need to interoperate with other Windows Runtime components (i.e., across the ABI boundary).
这篇关于Platform::String 真的这么没用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!